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;
        }
    };
  • 相关阅读:
    Django发送邮件功能
    Django视图中使用本地缓存
    Django中利用type动态操作数据库表
    Django扩展内置User类
    Django开发环境配置(win10)
    MySql隔离级别
    染色法判定二分图
    关押囚犯
    迷一样的牛poj2182
    poj3468 A Simple Problem with Integers
  • 原文地址:https://www.cnblogs.com/Bella2017/p/11260514.html
Copyright © 2011-2022 走看看