2021년 8월 12일 목요일

Leetcode 14th August

Leetcode 14th August

Group Anagrams

이 문제는 anagrams 가 같은 문자들 끼리 그룹화 해서 보여주는 문제
This question is return string list group by same anagrams

그래서 단순하게 저의 경우는 정렬 된 문자를 키로 가지는 map 만들고, 후에 값만 리턴 하는방식으로 문제를 해결하였습니다.
For solving this problem, i used make a Map, that is key, value store, then the key is sorted string, and value is string list, after generate map i return values.

Python

class Solution:
    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
        res = defaultdict(list)
        for s in strs:
            ss = "".join(sorted(s))
            res[ss].append(s)
        return [ v for i, v in res.items()]

요새 자바도 연습하고 있어서 똑같은 방식으로 자바 코드로도 한번 짜봤습니다.
i also try to write a code in java, because for now i learning Java

Java

class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {
        Map<String, List<String>> map = new HashMap();
        for (int i = 0; i < strs.length; i++) {
            char[] chars = strs[i].toCharArray();
            Arrays.sort(chars);
            String s = new String(chars);

            map.putIfAbsent(s, new ArrayList<>());
            map.get(s).add(strs[i]);
        }
        List<List<String>> res = new ArrayList();
        for (Map.Entry<String, List<String>> entry : map.entrySet()) {
            res.add(entry.getValue());
        }

        return res;
    }
}

댓글 없음:

댓글 쓰기