💻 Coding Problems Solving/Hash | HashMap
[LeetCode] Group Anagrams
Kim_dev
2023. 7. 18. 20:54
1. 문제 : https://leetcode.com/problems/group-anagrams/description/
2. 풀이
key를 만들어 활용하는게 중요
key까지 비교할 필요 x
3. 코드
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
HashMap<String, Integer> map = new HashMap<>();
List<List<String>> items = new ArrayList();
int k = 0;
for(String str : strs){
// key 생성하기.
char[] strChars = str.toCharArray();
Arrays.sort(strChars);
String key = new String(strChars);
if(map.get(key) != null){
int n = map.get(key);
List<String> item = items.get(n);
item.add(str);
items.set(n, item);
}else{
map.put(key, k++);
ArrayList<String> item = new ArrayList<>();
item.add(str);
items.add(item);
}
}
return items;
}
}