首页 > 其他 > 详细

Leetcode: Anagrams

时间:2014-12-10 22:26:02      阅读:267      评论:0      收藏:0      [点我收藏+]

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

Note: All inputs will be in lower-case.

分析:此题的题意不是很明确,意思重新表述应该是一组string里面,有几个是anagram,找出这几个string。因为anagram具有相同个数的字符只是顺序有所改变,我们可以将string中字符排序后,再用一个unordered_map将anagram的几个string放到一起。代码如下:

class Solution {
public:
    vector<string> anagrams(vector<string> &strs) {
        vector<string> result;
        unordered_map<string, vector<string> > group;
        for(auto i:strs){
            string tmp = i;
            sort(tmp.begin(), tmp.end());
            group[tmp].push_back(i);
        }
        for(auto i = group.begin(); i != group.end(); i++){
            if(i->second.size() > 1)
                result.insert(result.end(), i->second.begin(), i->second.end());
        }
        return result;
    }
};

 

Leetcode: Anagrams

原文:http://www.cnblogs.com/Kai-Xing/p/4156282.html

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