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

 class Solution{
public:
vector<string> anagrams(vector<string> &strs){
map<string,vector<string>> m;
vector<string> res;
for(int i = ; i < strs.size() ; i++){
string s = strs[i];
sort(s.begin(),s.end());//排序
m[s].push_back(strs[i]);//插入map
} for(map<string,vector<string>>::iterator i = m.begin(); i != m.end(); i++){
if((i->second).size() > )
for(int it = ; it < (i->second).size();it++)
res.push_back((i->second)[it]);//输出
}
return res;
}
};

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

 
 
上一篇:CString 转换成 char *


下一篇:SQLI DUMB SERIES-3