[Leetcode]49. Group Anagrams(x)

2024. 7. 31. 08:58java/javaAlgorithm

1. problem :

https://leetcode.com/problems/group-anagrams/description/

 

2. solution 1 :

public class Solution {
    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[] charArray = str.toCharArray();
            Arrays.sort(charArray);
            String sortedStr = new String(charArray);

            if (!map.containsKey(sortedStr)) {
                map.put(sortedStr, new ArrayList<>());
            }
            map.get(sortedStr).add(str);
        }
        return new ArrayList<>(map.values());
    }
}

This is chatgpt 4o solution. The key point in this problem is just sort the str then using this like key. 

 

3. solution 2 : 

class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {
        Map<String, List<String>> res = new HashMap<>();

        for (String s : strs) {
            int[] count = new int[26];

            for (char c : s.toCharArray()) {
                count[c - 'a']++;
            }

            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < 26; i++) {
                sb.append('#');
                sb.append(count[i]);
            }
            String key = sb.toString();
            
            if (!res.containsKey(key)) {
                res.put(key, new ArrayList<>());
            }
            res.get(key).add(s);
        }

        return new ArrayList<>(res.values());
    }
}

이 solution은 neetcode가 제공한 solution이다. str을 뽑아서 각각의 char를 배열에 증가하고, string builder를 이용해서 메모리를 절약하는 방법이라고 한다. 그리고  이 str을 key로 사용한다. 

'java > javaAlgorithm' 카테고리의 다른 글

[Leetcode]1004. Max Consecutive Ones III(x)  (0) 2024.07.31
[Leetcode]15. 3Sum(x)  (0) 2024.07.30
[Leetcode]1. Two Sum  (0) 2024.07.30
[Leetcode]242. Valid Anagram  (0) 2024.07.30
[Leetcode]217. Contains Duplicate  (0) 2024.07.30