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.
题目链接:https://leetcode.com/problems/group-anagrams/
思路:这题复杂度有待降低,cmp函数中先把每个string按字典序整好,然后对strs排序,然后分组的时候,再排序比较
class Solution {
public:
static bool comp(string s1,string s2)
{
sort(s1.begin(),s1.end());
sort(s2.begin(),s2.end());
return s1<s2;
}
vector<vector<string>> groupAnagrams(vector<string>& strs) {
vector<vector<string>> res;
vector<string> tmp;
int len=strs.size();
if(len==0)
return res;
if(len==1)
{
tmp.push_back(strs[0]);
res.push_back(tmp);
tmp.clear();
return res;
}
sort(strs.begin(),strs.end(),comp);
for(int i=0;i<strs.size();i++)
{
if(i==0)
{
tmp.push_back(strs[0]);
}
else
{
string s1=strs[i],s2=strs[i-1];
sort(s1.begin(),s1.end());
sort(s2.begin(),s2.end());
if(s1==s2)
{
tmp.push_back(strs[i]);
}
else
{
res.push_back(tmp);
tmp.clear();
tmp.push_back(strs[i]);
}
}
}
res.push_back(tmp);
return res;
}
};
可以使用map来,和我的思路一样,但是人家使用的工具很好哦,学习到了
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
unordered_map<string, vector<string>> count;
int i = 0;
for (auto s : strs)
{
sort(s.begin(), s.end());
count[s].push_back(strs[i++]);
}
vector<vector<string>> res;
for (auto n : count){
sort(n.second.begin(), n.second.end());
res.push_back(n.second);
}
return res;
}
};
复杂度降低了很多。虽然仅供参考,但这个确实好了很多
java版本
class Solution {
/**
2024.6.16
思路很简单,一个map记录同样的字符串对应的单词有哪些,比如abc作为key,value可以是bac,cab这种
那就是遍历字符串数据,然后遍历每个字符串的时候,先给字符串排序,把bac,cab这种都排序成abc这种
最后把map的value变成一个二维list就可以了
*/
public List<List<String>> groupAnagrams(String[] strs) {
// if(strs==null || strs.length==0){
// return new ArrayList<>();
// }
Map<String,List<String>> map=new HashMap<>();
for(String str:strs){
// 字符串转char数组得记忆一下
char[] chars=str.toCharArray();
// 字符串数据的排序要记录下,Arrays.sort()
Arrays.sort(chars);
String tmp=new String(chars);
if(map.get(tmp)==null){
map.put(tmp,new ArrayList<>());
}
map.get(tmp).add(str);
}
// MAP.values()拿到所有value值,然后new一个ArrayList
return new ArrayList(map.values());
}
}