标签:
The key to solving this problem is to design a hash table to record the information. This link posts a nice desing using an unordered_map. I rewrite the code below.
1 class Solution { 2 public: 3 vector<string> anagrams(vector<string>& strs) { 4 unordered_map<string, vector<int> > mp; 5 int n = strs.size(); 6 for (int i = 0; i < n; i++) { 7 string s = strs[i]; 8 sort(s.begin(), s.end()); 9 mp[s].push_back(i); 10 } 11 vector<string> anagram; 12 for (auto pr : mp) { 13 vector<int> indexes = pr.second; 14 if (indexes.size() > 1) { 15 int m = indexes.size(); 16 for (int i = 0; i < m; i++) 17 anagram.push_back(strs[indexes[i]]); 18 } 19 } 20 return anagram; 21 } 22 };
标签:
原文地址:http://www.cnblogs.com/jcliBlogger/p/4694339.html