49. Group Anagrams
Given an array of strings, group anagrams together.
Example:
Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
Output:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]
Note:
All inputs will be in lowercase.
The order of your output does not matter.
字符串題目
題意:字母異位詞,單詞組成的字母相同秆乳,順序不同
思路:
在原始信息和哈希映射使用的實(shí)際鍵之間建立映射關(guān)系懦鼠。 在這里體現(xiàn)為,將單詞字母按字母表順序排列屹堰,若排列結(jié)果相同肛冶,則為字母異位詞
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
unordered_map<string,vector<string>>hash;
for(auto s:strs)
{
string temp=s;
sort(temp.begin(),temp.end());
hash[temp].push_back(s);
}
int len=hash.size();
vector<vector<string> >ans(len);
int index=0;
for(auto i:hash)
{
ans[index++]=i.second;
}
return ans;
}
};
ps:
對(duì)string類型數(shù)據(jù)進(jìn)行字符串內(nèi)排序
代碼:
string str;
while(cin>>str){
int len = str.length();
sort(str.begin(), str.end());
cout<<str<<endl;
}
輸入:dcba
輸出:abcd