Given an array of strings, group anagrams together.
For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"]
, Return:
[ ["ate", "eat","tea"], ["nat","tan"], ["bat"]]my initial answer:class Solution {public: vector<vector<string>> groupAnagrams(vector<string>& strs) { set<char> charSet; vector<int> indexSet; map<set<char>,vector<int>> myMap; vector<vector<string>> result; vector<string> temPResult; for(int i = 0; i < strs.size(); i ++){ string tempStr = strs[i]; set<char> tempCharSet; vector<int> tempIndexSet; for(int j = 0; j < tempStr.size(); j ++){ tempCharSet.insert(tempStr[i]); } map<set<char>,vector<int>>::iterator it = myMap.find(tempCharSet); if(it == myMap.end()){ tempIndexSet.push_back(i); myMap.insert(make_pair(tempCharSet,tempIndexSet)); } else ((*it).second).push_back(i); } map<set<char>,vector<int>>::iterator it = myMap.begin(); while(it != myMap.end()){ indexSet = (*it).second; for(int i = 0; i < indexSet.size(); i ++){ tempResult.push_back(strs[i]); } result.push_back(tempResult); tempResult.clear(); it ++; } return result; }}; 但是在最长的那个case,超时了,后来看了别人的算法,改进了。class Solution {public: vector<vector<string>> groupAnagrams(vector<string>& strs) { map<string,vector<string>> myMap; for(int i = 0; i < strs.size(); i ++){ string temp = strs[i]; sort(temp.begin(),temp.end()); myMap[temp].push_back(strs[i]); } vector<vector<string>> result; map<string,vector<string>>::iterator it = myMap.begin(); vector<string> temp; while(it != myMap.end()){ temp = (*it).second; result.push_back(temp); it ++; } return result; }};
新闻热点
疑难解答