题目:49. 字母异位词分组
思路:哈希表。将每个字符串升序排序,然后采用哈希表即可。
C++版本:
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
//哈希表
unordered_map<string,vector<string>> mp;
//遍历每一个字符串
for(auto s:strs){
//对字符串进行排序
string t=s;
sort(t.begin(),t.end());
//哈希表来记录
mp[t].push_back(s);
}
vector<vector<string>> v;
for(auto x:mp){
v.push_back(x.second);
}
return v;
}
};
JAVA版本:
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
//哈希表
Map<String,List<String>> mp=new HashMap<String,List<String>>();
//遍历每一个字符串
for(String s:strs){
//对字符串进行排序
char[] c=s.toCharArray();
Arrays.sort(c);
String key=new String(c);
//哈希表来记录
List<String> tmp=mp.getOrDefault(key,new ArrayList<String>());
tmp.add(s);
mp.put(key,tmp);
}
return new ArrayList<List<String>>(mp.values());
}
}
标签:String,49,strs,mp,哈希,字符串,new,热题
From: https://blog.csdn.net/weixin_46028214/article/details/143816567