-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAnagrams.cpp
More file actions
48 lines (46 loc) · 1.12 KB
/
Copy pathAnagrams.cpp
File metadata and controls
48 lines (46 loc) · 1.12 KB
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include<iostream>
#include<map>
#include<vector>
#include<string>
#include<algorithm>
using namespace std;
class Solution {
public:
vector<string> anagrams(vector<string> &strs) {
if(strs.empty())
return vector<string>();
map<string,int> mp;
vector<string> ret;
size_t i;
for(i=0;i<strs.size();i++)
{
string s=strs[i];
sort(s.begin(),s.end());
//第一次直接插入map中
if(mp.find(s)==mp.end())
{
mp[s]=i;
}
else
{
//第二次,需要将第一个插入map中的string也放入vector中,以后就不要放了
if(mp[s]>=0)
{
ret.push_back(strs[mp[s]]);
mp[s]=-1;
}
ret.push_back(strs[i]);
}
}
return ret;
}
};
int main()
{
Solution s;
vector<string> str={"tea","and","ate","eat","den"};
vector<string> result=s.anagrams(str);
for(auto s:result)
cout<<s<<" ";
cout<<endl;
}