栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

【数据结构基础

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【数据结构基础

原题链接:Leetcode 49. Group Anagrams

Given an array of strings strs, group the anagrams together. You can return the answer in any order.

An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

Example 1:

Input: strs = ["eat","tea","tan","ate","nat","bat"]
Output: [["bat"],["nat","tan"],["ate","eat","tea"]]

Example 2:

Input: strs = [""]
Output: [[""]]

Example 3:

Input: strs = ["a"]
Output: [["a"]]

Constraints:

  • 1 <= strs.length <= 104
  • 0 <= strs[i].length <= 100
  • strs[i] consists of lowercase English letters.

方法一:排序 思路:

字母异位词值的顺序不同,但是进过排序后得到的字符串是相同的
那么就可以用排序后的字符串作为key,字母异位词链表作为value,维护一个哈希表
最后将哈希表中的内容取出来放到数组中返回即可

C++代码:
class Solution {
public:
    vector> groupAnagrams(vector& strs) {
        // <排序后的单词, 字母异位词链表>(有点像拉链法)
        unordered_map> mp;

        // 字母异位词排序之后是相同的
        for (auto str: strs) {
            string key = str;
            sort(key.begin(), key.end());
            mp[key].emplace_back(str);
        }

        vector> ans;
        // 每一个value都是一个包含同源异位词的数组
        for (auto it = mp.begin(); it != mp.end(); ++it) {
            ans.emplace_back(it->second);
        }
        return ans;
    }
};
复杂度分析:
  • 时间复杂度:O(nklogk),遍历需要n,然后遍历每个单词的过程需要klogk的排序时间,k为单词最大长度
  • 空间复杂度:O(nk),n为单词数目,k为单词最大长度,哈希表不会超过nk这个范围
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1029502.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号