Given a collection of strings, write a function that can group the anagrams together. You can return the answer in any order.
Test collection:
["able", "bable", "bubble", "emit", "glare", "item", "large", "horse", "serve", "shore", "song", "time", "verse"]
这道题的核心是把“字母组成相同但顺序不同”的字符串分到同一组,典型解法是用哈希表按“规范化后的字符串”分桶。常见做法是把每个单词排序后作为 key,例如 <code>eat</code>、<code>tea</code>、<code>ate</code> 排序后都变成 <code>aet</code>,从而被放进同一个列表;如果字符串只包含小写字母,也可以用 26 个字母的频次数组生成唯一签名。这样能把所有 anagram 高效归类,时间复杂度通常优于两两比较。
正文完