Given an array of strings, return all groups of strings that are anagrams.
Note: All inputs will be in lower-case.
题意是,回文如 eat ate tea都是回文。
明白题意就很好办了。map里的元素两种:value为负说明已经入vector。若为正,表示第一次出现,具体位置是value。再次相遇则value改为负且最初位置和当前位置串入vector
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30 |
class
Solution { public : vector<string> anagrams(vector<string> &strs) { vector<string> re; map<string, int > mm; for ( int
i = 0 ; i < strs.size();i++) { string s = strs[i]; sort(s.begin(),s.end()); if (mm.find(s) == mm.end()) { mm[s]=i; } else { if (mm[s] >= 0) { re.push_back(strs[mm[s]]); re.push_back(strs[i]); mm[s] = -1; } else
if (mm[s] == -1) { re.push_back(strs[i]); } } } return
re; } }; |
原文:http://www.cnblogs.com/pengyu2003/p/3594928.html