首页 > 其他 > 详细

Anagrams

时间:2014-04-05 10:41:12      阅读:390      评论:0      收藏:0      [点我收藏+]

Given an array of strings, return all groups of strings that are anagrams.

Note: All inputs will be in lower-case.

Solution: Sort the string to see if they‘re anagrams.

bubuko.com,布布扣
 1 class Solution {
 2 public:
 3     vector<string> anagrams(vector<string> &strs) {
 4         map<string,vector<int> > hashmap; // apply hashmap (BST)
 5         for(int i = 0; i < strs.size(); i++) {
 6             string s = strs[i];
 7             sort(s.begin(), s.end());
 8             hashmap[s].push_back(i);
 9         }
10         
11         vector<string> res;
12         for(map<string,vector<int> >::iterator it = hashmap.begin(); it != hashmap.end(); it++) {
13             vector<int>& tmp = it->second;
14             for(int i = 0; i < tmp.size(); i++) {
15                 if(tmp.size() > 1) {
16                     res.push_back(strs[tmp[i]]);
17                 }
18             }
19         }
20         return res;
21     }
22 };
bubuko.com,布布扣

 

Anagrams,布布扣,bubuko.com

Anagrams

原文:http://www.cnblogs.com/zhengjiankang/p/3646362.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!