Skip to content

Latest commit

 

History

History
88 lines (55 loc) · 1.7 KB

49.Group-Anagrams.md

File metadata and controls

88 lines (55 loc) · 1.7 KB

49. Group Anagrams

題目


Given an array of strings strs, group the anagrams together. You can return the answer in any order.

An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

Example 1:

Input: strs = ["eat","tea","tan","ate","nat","bat"]
Output: [["bat"],["nat","tan"],["ate","eat","tea"]]

Example 2:

Input: strs = [""]
Output: [[""]]

Example 3:

Input: strs = ["a"]
Output: [["a"]]

Constraints:

  • 1 <= strs.length <= 10^4
  • 0 <= strs[i].length <= 100
  • strs[i] consists of lowercase English letters.

思路


Code


  • GoLang

    Runtime 10ms Beats 99.73%

    Memory 7.81mb Beats 55.78%

    Time Complexity: O(m * n* 26) , m is number of strings, n is average length of string.

    Space Complexity: O(m*n) , m is number of strings, n is average length of string.

    func groupAnagrams(strs []string) [][]string {
        anagramsMap := make(map[[26]int][]string)
        
        for _, s := range strs {
            var count [26]int
            for _, c := range s {
                count[c - 'a']++
            }
    
            anagramsMap[count] = append(anagramsMap[count], s)
        }
    
        result := make([][]string, len(anagramsMap))
        index := 0
        for _, v := range anagramsMap {
            result[index] = v
            index++
        }
    
        return result
    }

Reference