标签:
Given an array of strings, return all groups of strings that are anagrams.
Note: All inputs will be in lower-case.
我理解之后提交的代码:
1 #include "stdafx.h" 2 #include <vector> 3 #include <string> 4 #include <map> 5 #include <algorithm> 6 #include <iostream> 7 using namespace std; 8 9 class Solution 10 { 11 public: 12 vector<string> anagrams(vector<string> &strs) 13 { 14 map<string,vector<int>> exists; 15 for(int index =0 ; index < strs.size(); index++)//!!!边界 16 { 17 string s;//sort()会改变字符串,故需要临时变量存储 18 s = strs[index]; 19 sort(s.begin(), s.end()); 20 21 exists[s].push_back(index); //直接插入即可 22 23 } 24 vector<string> result; 25 for(auto const &ip : exists) 26 { 27 if(ip.second.size() > 1)//等于1,没有易位构词;注意表达方式!!! 28 { 29 for(auto const &it : ip.second) 30 result.push_back(strs[it]); 31 } 32 } 33 34 //for(auto it : result) 35 // cout << it << " "; 36 //cout << endl; 37 return result; 38 } 39 }; 40 int main() 41 { 42 Solution sol; 43 string data[] ={"tea","and","ate","nad","eat","dna","dan","tt"}; 44 vector<string> test(data,data+8); 45 sol.anagrams(test); 46 47 return 0; 48 }
网上另一种解法,虽然也能输出,但是,相同易位构词并不会在一类全部输出之后,再输出另一类;但它需要的存储空间比较小
1 class Solution { 2 public: 3 vector<string> anagrams(vector<string> &strs) 4 {//网上代码 5 string s; 6 map<string, int> anagram; 7 vector<string> res; 8 for (int i = 0; i < strs.size(); ++i) 9 { 10 s = strs[i]; 11 sort(s.begin(), s.end()); 12 if (anagram.find(s) == anagram.end()) 13 { 14 anagram[s] = i;//第一次出现此类易位构词 15 } 16 else 17 { 18 if (anagram[s] >= 0) 19 {//此类第二次出现,将第一次输出 20 res.push_back(strs[anagram[s]]); 21 anagram[s] = -1; 22 } 23 //在本类已存在过的情况下[已置为-1],会输出所有,包括第二次输出的 24 res.push_back(strs[i]); 25 } 26 } 27 return res; 28 } 29 };
标签:
原文地址:http://www.cnblogs.com/dreamrun/p/4527580.html