본문 바로가기
알고리즘

[Swift] LeetCode - 49. Group Anagrams

by 고고 2022. 2. 14.

문제: https://leetcode.com/problems/group-anagrams/

 

Group Anagrams - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

 

 

import Foundation

class Solution {
    func groupAnagrams(_ strs: [String]) -> [[String]] {
        var dict = [String: [String]]()
        
        for str in strs {
            let key = String(str.sorted())
            
            if dict[key] == nil {
                dict[key] = [str]
            } else {
                dict[key]!.append(str)
            }
        }
        
        return Array(dict.values)
    }
}

print(Solution().groupAnagrams(["eat","tea","tan","ate","nat","bat"])) // [["bat"],["nat","tan"],["ate","eat","tea"]]
print(Solution().groupAnagrams([""]))
print(Solution().groupAnagrams(["a"]))
print(Solution().groupAnagrams(["ddddddddddg","dgggggggggg"]))

댓글