LintCode-乱序字符串

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

样例

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

返回 ["lint","inlt","intl"]

注意

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

分析:对每次字母进行排序,然后用hash表记录个数就行

代码:

class Solution {
public:    
    /**
     * @param strs: A list of strings
     * @return: A list of strings
     */
    vector<string> anagrams(vector<string> &strs) {
        // write your code here
        map<string,int> m;
        for(auto s:strs)
        {
            sort(s.begin(),s.end());
            m[s]++;
        }
        vector<string> ret;
        for(auto s:strs)
        {
            auto temp = s;
            sort(temp.begin(),temp.end());
            if(m[temp]>1)
                ret.push_back(s);
        }
        return ret;
    }
};


你可能感兴趣的:(面试,lintcode)