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

Leetcode: Anagrams

时间:2014-12-10 22:28:44      阅读:294      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   ar   color   sp   for   on   div   

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

标签:style   blog   io   ar   color   sp   for   on   div   

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

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