[LeetCode]Group Anagrams

Group Anagrams

Given two strings s and t, write a function to determine if t is an anagram of s.

For example,
s = "anagram", t = "nagaram", return true.
s = "rat", t = "car", return false.

Note:
You may assume the string contains only lowercase alphabets.

 

如果这题用Valid Anagram的方法直接,会Time Limit。

间接的使用这种方法。

如果两个string排序后相同,他们就是Anagram的,所以可以使用排序后的string作为Hash Table的key,值就是这些Anagram的stings,结果push_back的时候按字典排下序就好了。

 1 class Solution {
 2 public:
 3     vector<vector<string>> groupAnagrams(vector<string>& strs) {
 4         vector<vector<string>> result;
 5         unordered_map<string,vector<string>> showed;
 6         for(int i=0;i<strs.size();i++)
 7         {
 8             string t=strs[i];
 9             sort(t.begin(),t.end());
10             showed[t].push_back(strs[i]);
11         }
12         for(unordered_map<string,vector<string>>::iterator iter=showed.begin();iter!=showed.end();iter++)
13         {
14             vector<string> temp = iter->second;
15             sort(temp.begin(),temp.end());
16             result.push_back(temp);
17         }
18         
19         return result;
20     }
21 };

 

posted @ 2015-08-19 18:46  Sean_le  阅读(178)  评论(0)    收藏  举报