zoukankan      html  css  js  c++  java
  • (hash) leetcode 49. Group Anagrams

    思路:哈希表,用map实现,(key, value) = (strs[i], index).

    将字符串按字典序排序后,若能在map中找到相应的字符串,则对应value+1(value存储的是单词中同构体集合在output中的index),如 ["ate", "eat", "tea"] 对应索引为0; ["nat", tan"] 对应索引为1...

    class Solution {
    public:
        vector<vector<string>> groupAnagrams(vector<string>& strs) {
            //hash
            vector<vector<string>> result;
            map<string, int> index;
            int cnt = 0;   //记录anagram 个数
            for(int i=0; i<strs.size(); ++i){
                string tmp = strs[i];
                sort(tmp.begin(), tmp.end());  //按字典序排列
                if(index.find(tmp) == index.end()){
                    //未在map中找到tmp
                    index[tmp] = cnt;
                    cnt++;
                    vector<string> tmpstr;
                    tmpstr.push_back(strs[i]);
                    result.push_back(tmpstr);
                }
                else
                    result[index[tmp]].push_back(strs[i]);
            }
            return result;
        }
    };
    class Solution {
    public:
        vector<vector<string>> groupAnagrams(vector<string>& strs) {
            vector<vector<string>> res;    //返回值
            unordered_map<string, vector<string>> m;   //字符串与它的同构字符串之间的映射
            for(string str: strs){
                string t = str;
                sort(t.begin(),t.end());
                m[t].push_back(str);
            }
            for(auto a:m)
                res.push_back(a.second);
            return res;
        }
    };
  • 相关阅读:
    11月21日
    11月20日
    11月19日
    11月18日
    11月17日
    11月15日
    图文教程:在Mac上搭建Titanium的iOS开发环境
    经验
    IT术语的正确读法
    NSLog( @"%@", i );
  • 原文地址:https://www.cnblogs.com/Bella2017/p/11260514.html
Copyright © 2011-2022 走看看