首页 > 代码库 > LeetCode[Hash Table]: Anagrams

LeetCode[Hash Table]: Anagrams

Given an array of strings, return all groups of strings that are anagrams.
Note: All inputs will be in lower-case.

思路:对每一个单词的所有字母按照字典顺序排序,排序结果作为key,所有具有相同key的单词组合在一起成为一个Anagram group。最后返回所有的Anagram group。

class Solution {
public:
    vector<string> anagrams(vector<string> &strs) {
        vector<string> result;

        unordered_map<string, vector<string>> dict;
        for (auto word : strs)
            dict[getLetters(word)].push_back(word);

        for (auto wordGroup : dict)
            if (wordGroup.second.size() > 1)
                result.insert(result.end(), wordGroup.second.begin(), wordGroup.second.end());

        return result;
    }

private:
    string getLetters(string word) {
        string letters;
        for    (auto letter : word) {
            int i;
            for (i = 0; i < letters.size(); ++i)
                if (letters[i] > letter)
                    break;

            letters.insert(letters.begin() + i, letter);
        }

        return letters;
    }
};


上面的解法中,对每一个单词按照字典顺序排序采用自己写的插入排序算法,也可以采用<algorthm>中的sort函数。

class Solution {
public:
    vector<string> anagrams(vector<string> &strs) {
        vector<string> result;

        unordered_map<string, vector<string>> dict;
        for (auto word : strs){
            string tmp = word;
            sort(tmp.begin(), tmp.end());
            dict[tmp].push_back(word);
        }

        for (auto group : dict)
            if (group.second.size() > 1)
                result.insert(result.end(), group.second.begin(), group.second.end());

        return result;
    }
};


LeetCode[Hash Table]: Anagrams