FRTKL

49. Group Anagrams (Easy)

Problem

https://leetcode.com/problems/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"]]

Solution

Go

func groupAnagrams(strs []string) [][]string {
    groups := make(map[string][]string)
    for _, str := range strs {
        b := []byte(str)
        sort.Slice(b, func(i, j int) bool {
            return b[i] < b[j]
        })
        key := string(b)
        groups[key] = append(groups[key], str)
    }
    
    ret := make([][]string, 0, len(groups))
    for _, v := range groups {
        ret = append(ret, v)        
    }
    return ret
}

PHP

class Solution {

    /**
     * @param String[] $strs
     * @return String[][]
     */
    function groupAnagrams($strs) {
        $res = [];
        foreach ($strs as $str) {
            $tmp = str_split($str);
            sort($tmp);
            $word = implode("", $tmp);
            $res[$word][] = $str;
        }
        return $res;
    }
}

Impression

  • それぞれの文字列をソートした状態でカテゴライズしてグループ化した
  • PHPはわりと簡単に書けた
  • GoはPHPのstr_split相当の処理を自前で書くのがやや時間がかかった
Written By Fukuaki TAKANO
fortkle icon

Engineering Manager at Connehito inc.
Please contact me via twitter. @fortkle