• 49. Group Anagrams (string, HashTable)


    Given an array of strings, group anagrams together.

    For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"]
    Return:

    [
      ["ate", "eat","tea"],
      ["nat","tan"],
      ["bat"]
    ]

    Note:

    1. For the return value, each inner list's elements must follow the lexicographic order.
    2. All inputs will be in lower-case.

    思路:

    anagram: 由颠倒字母而成的单词

    anagram是否出现过,可以通过Hashmap,但是由于anagram无关乎字母出现的顺序,所以也可以将字母排序后再比较字符串。

    class Solution {
    public:
        vector<vector<string>> groupAnagrams(vector<string>& strs) {
            if (strs.size() <= 0) return result;
            
            vector<vector<string>> result;
            map<string,int> anagram;
            int resIndex = 0;
            string s;
            
            for (int i = 0; i < strs.size(); ++i)
            {
                s = strs[i];
                sort(s.begin(), s.end()); //anagram无关乎字母顺序,所以将string按字母排序后再比较
                if (anagram.find(s) == anagram.end()) { //如果还没有出现过该anagram
                    vector<string> item;
                    item.push_back(strs[i]);
                    result.push_back(item);
                    anagram.insert(make_pair(s, resIndex++));
                } else {
                    result[anagram[s]].push_back(strs[i]);
                }
            }
            
            //each inner list's elements must follow the lexicographic order
            for(int i = 0; i < result.size(); i++){
                sort(result[i].begin(), result[i].end());
            }
            return result;
        }
    };
  • 相关阅读:
    linux指令备份
    jdk安装
    java-成员变量的属性与成员函数的覆盖
    Codeforces Round #384 (Div. 2) E
    Codeforces Round #384 (Div. 2) ABCD
    Codeforces Round #383 (Div. 2) D 分组背包
    ccpcfinal总结
    HDU 3966 & POJ 3237 & HYSBZ 2243 & HRBUST 2064 树链剖分
    HDU 5965 枚举模拟 + dp(?)
    Educational Codeforces Round 6 E dfs序+线段树
  • 原文地址:https://www.cnblogs.com/qionglouyuyu/p/4854871.html
Copyright © 2020-2023  润新知