LeetCode--Anagrams

 1 /*************************************************************************
 2     > File Name: Anagrams.cpp
 3     > Author: zhoukang1991
 4     > Mail: zhoukang199191@126.com 
 5     > Created Time: 2014年08月14日 星期四 23时36分28秒
 6  ************************************************************************/
 7 
 8 #include <iostream>
 9 #include <string>
10 #include <vector>
11 #include <algorithm>
12 #include <map>
13 using namespace std;
14 
15 //思路:先把sort之后的string插入map,然后当出现了新的时候
16 //就把之前第一次发现的string插入结果中去
17 class Solution{
18     public:
19         vector<string> anagrams(vector<string> &strs){
20             vector<string> res;
21             map<string,int> mp;
22             for(int i =0 ; i < strs.size() ; ++i){
23                 string ss = strs[i];
24                 sort(ss.begin(),ss.end());
25                 if(mp.find(ss) != mp.end()){
26                     res.push_back(strs[i]);
27                     if(mp[ss] != -1){
28                         res.push_back(strs[mp[ss]]);
29                         mp[ss] = -1;
30                         //因为第一次出现的时候不能判断后面有没有它的angrams
31                         //所以在这个时候再插入
32                     }
33                 }
34                 else {
35                     mp[ss] = i;
36                 }
37             }
38             return res;
39         }
40 };
41 int main(){
42     return 0;
43 }
原文地址:https://www.cnblogs.com/cane/p/3912226.html