首页 > 其他 > 详细

LeetCode 49: Anagrams

时间:2015-03-24 01:24:26      阅读:284      评论:0      收藏:0      [点我收藏+]

题目描述:

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

Note: All inputs will be in lower-case.

思路:

题目的意思呢,就是寻找一组字符串中,字符串使用相同数量的相同字符的两个字符串互为anagrams,把这样的字符串输出。

明白了题目的意思,我们可以对每个字符串进行排序,然后将排序后的字符串作为该字符串的哈希值,保存每个哈希值的所有字符串。如果该哈希值的字符串的个数大于1,也就是说存在anagrams

代码:

class Solution {
public:
    vector<string> anagrams(vector<string> &strs) {
		map<string,vector<string> > map_str;
		vector<string> vec_str;
		for(int i =0;i<strs.size();i++){
			string temp= strs[i];
			sort(temp.begin(),temp.end());
			map_str[temp].push_back(strs[i]);
		}
		for(map<string,vector<string> >::iterator it=map_str.begin(); it!=map_str.end(); it++){
			for(vector<string>::iterator it2 = it->second.begin(); it2!=it->second.end() &&(it->second).size()>1; it2++){
				vec_str.push_back(*it2);
			}
		}
		return vec_str;
	}
};

 

LeetCode 49: Anagrams

原文:http://www.cnblogs.com/xiamaogeng/p/4361374.html

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