首页 > 代码库 > [LeetCode] Anagrams

[LeetCode] Anagrams

Given an array of strings, return all groups of strings that are anagrams.

Note: All inputs will be in lower-case.

用map记录出现的string的下标,避免了再次遍历。

class Solution {public:    vector<string> anagrams(vector<string> &strs) {        vector<string> result;        int len = strs.size();        map<string,int> strIndex;//key是string,value是对应在strs中的下标        for(int i=0;i<len;i++){            string s0 = strs[i];            sort(s0.begin(),s0.end());            if(strIndex.count(s0)==0)                strIndex[s0] = i;            else{                if(find(result.begin(),result.end(),strs[strIndex[s0]])==result.end())                    result.push_back(strs[strIndex[s0]]);                result.push_back(strs[i]);            }                }//end for        return result;    }//end func};