题目:
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
时间: 2024-11-06 12:34:59