亂序字符串
描述
筆記
數據
評測
給出一個字符串數組S,找到其中所有的亂序字符串(Anagram)。如果一個字符串是亂序字符串,那麼他存在一個字母集合相同,但順序不同的字符串也在S中。
注意事項
所有的字符串都只包含小寫字母
您在真實的面試中是否遇到過這個題? Yes
樣例
對於字符串數組 [“lint”,”intl”,”inlt”,”code”]
返回 [“lint”,”inlt”,”intl”]
class Solution {
public:
/**
* @param strs: A list of strings
* @return: A list of strings
*/
vector<string> anagrams(vector<string> &strs) {
// write your code here
map<string,int> m;vector<string> v;
for(auto s:strs){
sort(s.begin(),s.end());
m[s]++;
}
for(auto &s:strs){
string s1=s;
sort(s1.begin(),s1.end());
if(m[s1]>1)
v.push_back(s);
}
return v;
}
};