problem:
Given an array of strings, return all groups of strings that are anagrams.
Note: All inputs will be in lower-case.
Hide Tags
题意:给定多余两组的字符串,找出其中所有的满足以下条件的字符串:(1)字符串的字符种类和对应的数量一样(2)各个字符的位置不作区分
thinking:
(1)很直接想到用hash table来解决这类问题
(2)也可以借用STL map,更加便捷,主键key 存放排序好的string,value 存放指向该string的指针
map<string, vector<const string *> > mapAnagram;
code:
class Solution { public: vector<string> anagrams(vector<string> &strs) { vector<string> ret; map<string, vector<const string *> > mapAnagram; for (vector<string>::const_iterator it = strs.begin(); it != strs.end(); ++it) { string key(*it); sort(key.begin(), key.end()); mapAnagram[key].push_back(&*it); } for (map<string, vector<const string *> >::const_iterator it = mapAnagram.begin(); it != mapAnagram.end(); ++it) { if (it->second.size() > 1) { for (vector<const string *>::const_iterator itstr = it->second.begin(); itstr != it->second.end(); ++itstr) { ret.push_back(**itstr); } } } return ret; } };
时间: 2024-10-31 22:24:12