[LeetCode] 49. Group Anagrams(分组相同字母异序词)

Description

Given an array of strings strs, group the anagrams together. You can return the answer in any order.
给定一个字符串数组 strs,将相同字母异序词分组。你可以以任意顺序返回答案。

An Anagram is a word or phase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
相同字母异序词是由另一个词或词组通过调换字母顺序生成的词或词组。

Examples

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 lower-case English letters.

Solution

按照题目的定义做即可。可以按照标签里所说,使用哈希表统计字符个数。以下单行写法纯粹是个人的恶趣味,思路就是相同字母异序词既然是通过字母重排得到的,那么互为相同字母异序词的两个单词,其字母排序后生成的单词应该也是相同的。代码如下:

class Solution {
    fun groupAnagrams(strs: Array<String>): List<List<String>> {
        return strs.groupBy { it.toCharArray().sorted().joinToString(separator = "") }.values.toList()
    }
}
原文地址:https://www.cnblogs.com/zhongju/p/13917644.html