LeetCode ---Anagrams() 详解

Notice:

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

Note: All inputs will be in lower-case.

For example:

Input:  ["tea","and","ate","eat","den"]

Output:   ["tea","ate","eat"]

Interface: vector<string>anagrams(vector<string>&strs);

 

解题思路:

有相同字母构成的不同序列的单词,排过序后肯定是一样的,所以可以存放在map中,最后从map中取出value个数大于1的值,也就是字母相同构成的字母“们”

举个例子["ate","tea","aet","eat","hgt","gf","atg","gat"]对于这个容器而言,我们先对ate字典排序,变成aet,然后放入map中,这里的map构造为

map<string,vector<string>>

对7个单词遍历后,map的构成如下:

key        value[0] value[1] value[2] value[3]

aet    ate         tea         aet         eat

ght       hgt

fg         gf

agt        atg        gat

之后遍历map,对于value个数大于1的单词“们”放入res数组中,

最后res数组中即为那些Anagrams

 这里会输出两组 Anagrams

 1 class Solution{
 2 public:
 3   vector<string> anagrams(vector<string> &strs){
 4     map<string,vector<string>> m;
 5     vector<string> res;
 6     for(int i = 0; i < strs.size() ; i++){
 7       string s = strs[i];
 8       sort(s.begin(),s.end());//排序
 9       m[s].push_back(strs[i]);//插入map
10     }
11 
12     for(map<string,vector<string>>::iterator i = m.begin(); i != m.end(); i++){
13       if((i->second).size() > 1)
14         for(int it = 0; it < (i->second).size();it++)
15           res.push_back((i->second)[it]);//输出
16     }
17     return res;
18   }
19 };

PS:必须深入理解STL中,map的用法,key-value可以取各种类型包括容器类型。size()等内建函数也是通用的。

 

 

 
 
posted @ 2014-07-09 15:45  肥磊  阅读(384)  评论(0编辑  收藏  举报