码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Anagrams

时间:2015-08-01 18:38:40      阅读:106      评论:0      收藏:0      [点我收藏+]

标签:

The key to solving this problem is to design a hash table to record the information. This link posts a nice desing using an unordered_map. I rewrite the code below.

 1 class Solution {
 2 public:
 3     vector<string> anagrams(vector<string>& strs) {
 4         unordered_map<string, vector<int> > mp;
 5         int n = strs.size();
 6         for (int i = 0; i < n; i++) {
 7             string s = strs[i];
 8             sort(s.begin(), s.end());
 9             mp[s].push_back(i);
10         }
11         vector<string> anagram;
12         for (auto pr : mp) {
13             vector<int> indexes = pr.second;
14             if (indexes.size() > 1) {
15                 int m = indexes.size();
16                 for (int i = 0; i < m; i++)
17                     anagram.push_back(strs[indexes[i]]);
18             }
19         }
20         return anagram;
21     }
22 };

 

[LeetCode] Anagrams

标签:

原文地址:http://www.cnblogs.com/jcliBlogger/p/4694339.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!