ID | Title | Difficulty | |
---|---|---|---|
Loading... |
49. Group Anagrams
Medium
LeetCode
Array, Hash Table, String, Sorting
Problem
Given an array of strings, group anagrams together.
Example:
Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
Output:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]
Constraints:
- $1 <= strs.length <= 10^4$
- 0 <= strs[i].length <= 100
- strs[i] consists of lowercase English letters.
Code
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
HashMap<String, List<String>> map = new HashMap<>();
for(String str : strs){
String sorted = helper(str);
if(!map.containsKey(sorted)){
map.put(sorted, new ArrayList<>());
}
map.get(sorted).add(str);
}
List<List<String>> res = new ArrayList<>();
for(List<String> temp : map.values()){
res.add(temp);
}
return res;
}
private String helper(String s){
char[] charArr = s.toCharArray();
Arrays.sort(charArr);
return new String(charArr);
}
}
按 <- 键看上一题!
48. Rotate Image
按 -> 键看下一题!
50. Pow(x, n)