【小白爬Leetcode49】7.1 字母异位词分组 Group Anagrams

【小白爬Leetcode49】7.1 字母异位词分组 Group Anagrams

Leetcode 315 m e d i u m \color{#FF4500}{medium} medium
点击进入原题链接:字母异位词分组 Group Anagrams

题目

Discription

Given an array of strings, group anagrams together.
在这里插入图片描述
Notes

  • All inputs will be in lowercase.
  • The order of your output does not matter.

思路一 给str排序

anagrams其实就是相同的字母,不同的排序罢了,那么对每个str排序,排序后的值作为哈希表的key,排序前的字符串push_back进value,即可。

class Solution {
public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
        std::unordered_map<std::string,std::vector<std::string>> map;
        for(int i=0;i<strs.size();i++){
            string tmp(strs[i]); //赋值一个临时变量进行排序(不能破坏原来的strs[i])
            std::sort(tmp.begin(),tmp.end(),less<char>());
            map[tmp].push_back(strs[i]); //排序后的anagram肯定是一样的tmp了,当作哈希表的key即可
        }
        std::vector<std::vector<std::string>> ans;
        for(auto it:map){ //把哈希表里所有的值都push进结果数组
            ans.push_back(it.second);
        }
        return ans;
    }
};

时间复杂度: 设每个字符串的平均长度为M,一共有N个字符串,最后排序后有n类字符串,那么排序的时间复杂度为O(MlogM),插入哈希表的时间为常数,遍历哈希表的时间为O(n),因此时间复杂度应该是O(N*MlogM) 和 **O(N*n)**中的最大值。
空间复杂度: 需要储存整个字符串

思路二 用vector当作key

还有一种以空间换取时间的思路是:设置一个长度为26的vector,记录一个字符串中每个字母出现的次数,并把这个vector当作哈希表的key。

class Solution {
public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
        std:map<std::vector<int>,std::vector<std::string>> map;
        for(int i=0;i<strs.size();i++){
            vector<int> v(26,0);
            for(int j=0;j<strs[i].size();j++){
                v[strs[i][j]-'a']++;
            }
            map[v].push_back(strs[i]);           
        }
        std::vector<std::vector<std::string>> ans;
        for(auto it:map){
            ans.push_back(it.second);
        }
        return ans;
    }
};

但是好像遇到了unordered_map没办法直接用vector<int>做key值的情况,C++知识太欠缺,可能要重载一些函数吧。所以这里用的map。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值