LeetCode: anagram

没写出来,很经典的一道题,可以用来练vector的迭代器使用, 答案是看网上的

 1 class Solution {

 2 public:

 3     vector<string> anagrams(vector<string> &strs) {

 4         // Start typing your C/C++ solution below

 5         // DO NOT write int main() function

 6         vector<string> reti;

 7         map<string, vector<string>> ret;

 8         for (int i = 0; i < strs.size(); i++) {

 9             string tmp = strs[i];

10             sort(tmp.begin(), tmp.end());

11             ret[tmp].push_back(strs[i]);

12         }

13         for (map<string, vector<string>>::iterator it = ret.begin(); it != ret.end(); it++) {

14             if ((it->second).size() > 1) {

15                 for (vector<string>::iterator it1 = (it->second).begin(); it1 != (it->second).end(); it1++) {

16                     reti.push_back(*it1);

17                 }

18             }

19         }

20         return reti;

21     }

22 };

 后来用了自己写的multimap的代码

 1 class Solution {

 2 public:

 3     vector<string> anagrams(vector<string> &strs) {

 4         // Start typing your C/C++ solution below

 5         // DO NOT write int main() function

 6         vector<string> ret;

 7         multimap<string, string> S;

 8         typedef multimap<string, string>::iterator ana_it;

 9         for (int i = 0; i < strs.size(); i++) {

10             string tmp = strs[i];

11             sort(tmp.begin(), tmp.end());

12             S.insert(make_pair(tmp, strs[i]));

13         }

14         for (ana_it it = S.begin(); it != S.end(); it++) {

15             if (S.count(it->first) > 1) {

16                 pair<ana_it, ana_it> pos = S.equal_range(it->first);

17                 while (pos.first != pos.second) {

18                     ret.push_back(pos.first->second);

19                     pos.first++;

20                 }

21                 it = pos.second, it--;

22             }

23         }

24         return ret;

25     }

26 };

 C#版:string是不能sort的,只能用ToCharArray转成字符数组进行排序,再new string转成字符串才行

 1 public class Solution {

 2     public List<string> Anagrams(string[] strs) {

 3         List<string> ans = new List<string>();

 4         Dictionary<string, List<string>> dic = new Dictionary<string, List<string>>();

 5         for (int i = 0; i < strs.Length; i++) {

 6             char[] tmp = strs[i].ToCharArray();

 7             Array.Sort(tmp);

 8             string newTmp = new string(tmp);

 9             if (dic.ContainsKey(newTmp)) dic[newTmp].Add(strs[i]);

10             else dic.Add(newTmp, new List<string>{strs[i]});

11         }

12         foreach (var s in dic) {

13             if (s.Value.Count > 1) {

14                 for (int i = 0; i < s.Value.Count; i++) {

15                     ans.Add(s.Value[i]);

16                 }

17             }

18         }

19         return ans;

20     }

21 }
View Code

 

你可能感兴趣的:(LeetCode)