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

【Anagrams】 cpp

时间:2015-05-11 21:30:23      阅读:206      评论:0      收藏:0      [点我收藏+]

标签:

题目:

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

Note: All inputs will be in lower-case.

代码:

class Solution {
public:
    vector<string> anagrams(vector<string>& strs) {
        vector<string> ret;
        map<string,vector<int> > str_indexs;
        // trans strs to key (sorted string) and value (indexs of strs that have same key) pairs
        for ( size_t i = 0; i < strs.size(); ++i )
        {
            string key = strs[i];
            std::sort(key.begin(), key.end());
            str_indexs[key].push_back(i);
        }
        // add the keys which occurs more than once
        for ( map<string,vector<int> >::iterator it = str_indexs.begin(); it!= str_indexs.end(); ++it )
        {
            if ( it->second.size()>1 )
            {
                for ( size_t k = 0; k < it->second.size(); ++k )
                {
                    ret.push_back(strs[it->second[k]]);
                }
            }
        }
        return ret;
    }
};

tips:

对于std::map的使用还不太熟悉,接着这道题也熟悉一下。

这道题非常经典,直接搜的AC code。学习了一下,把看过的几个blog记录在下面。

http://bangbingsyb.blogspot.sg/2014/11/leetcode-anagrams.html

http://www.cnblogs.com/AnnieKim/archive/2013/04/25/3041982.html

【Anagrams】 cpp

标签:

原文地址:http://www.cnblogs.com/xbf9xbf/p/4495424.html

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