lintcode-171-乱序字符串

171-乱序字符串

给出一个字符串数组S,找到其中所有的乱序字符串(Anagram)。如果一个字符串是乱序字符串,那么他存在一个字母集合相同,但顺序不同的字符串也在S中。

注意事项

所有的字符串都只包含小写字母

样例

对于字符串数组 ["lint","intl","inlt","code"]
返回 ["lint","inlt","intl"]

挑战

What is Anagram?

  • Two strings are anagram if they can be the same after change the order of characters.

标签

哈希表 字符串处理 优步 脸书

思路

利用排序和哈希表,所有的乱序字符串经过排序后会对应同一个字符串,所以以排序后的字符串为哈希表,记录此字符串出现次数,若出现不止一次,则为乱序字符串

code

class Solution {
public:    
    /**
     * @param strs: A list of strings
     * @return: A list of strings
     */
    vector<string> anagrams(vector<string> &strs) {
        // write your code here
        int size = strs.size(), i = 0;
        if (size <= 0) {
            return vector<string>();
        }

        vector<string> result;
        map<string, int> hash;
        for (i = 0; i < size; i++) {
            string temp = strs[i];
            sort(temp.begin(), temp.end());
            hash[temp]++;
        }
        for (i = 0; i < size; i++) {
            string temp = strs[i];
            sort(temp.begin(), temp.end());
            if (hash[temp] > 1) {
                result.push_back(strs[i]);
            }
        }
        return result;
    }
};
原文地址:https://www.cnblogs.com/libaoquan/p/7277933.html