- 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.
python
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
words = {}
res = []
for word in strs:
sortedword = str(sorted(word))
if sortedword in words:
res[words[sortedword]].append(word)
else:
res.append([word])
words[sortedword] = len(res) - 1
return res
tips:
word list的key值是字符串,值是res第几个数组
java:
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
List<List<String>> res = new ArrayList<List<String>>();
Map<String,Integer> mp = new HashMap<String,Integer>();
for(String str : strs){
char[] ch = str.toCharArray();
Arrays.sort(ch);
String s = new String(ch);
if(mp.containsKey(s)){
List li = res.get(mp.get(s));
li.add(str);
}
else{
List li = new ArrayList();
li.add(str);
res.add(li);
mp.put(s,res.size()-1);
}
}
return res;
}
}
tips:
先将字符串转换成字符数组吗,再将数组进行排序,接着在判断是否在map的key值中,在的话将字符串放入相应的List中,不在的话重新初始化一个列表,并将字符串放入。