알고리즘/String
Leet code (Medium): 49. Group Anagrams - Java
mezo
2024. 10. 27. 17:01
728x90
반응형
anagram 문제는 char[]로 만들어서 알파벳순으로 재정렬한 후, 찾는 것이 핵심이다.
여기선 HashMap을 사용해서 재정렬된 단어를 키로 해서 그단어의 anagram인 것들을 value에 넣는 방법을 사용했다.
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
Map<String, List<String>> map = new HashMap<>();
for(String word : strs){
// 단어를 알파벳순으로 재정렬
char[] chars = word.toCharArray();
Arrays.sort(chars);
String sorted = new String(chars);
// 재정렬한 단어가 없다면 List 초기화해서 넣음
if(!map.containsKey(sorted)){
map.put(sorted, new ArrayList<>());
}
// map에 추가
map.get(sorted).add(word);
}
return new ArrayList<>(map.values());
}
}
728x90
반응형