Description
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 <= 104
0 <= strs[i].length <= 100
strs[i]
consists of lowercase English letters.
Code
hash function 用英文字母加上出現頻率當作 key ,做成 string,以 abbac
為例,hash 值就是 a2b2c1
。
如果不加上英文字母本身,只單純將 26 個字母的頻率組成 string 的話,下面這個 case 就會導致不同的 string 對應到相同的 hash string key。
Example case: strs = ["bdddddddddd","bbbbbbbbbbc"]
Time Complexity: O(n), Space Complexity: O(n)
Time Complexity: O(nlogn), Space Complexity: O(n)
也可以對每個 string 都要先 sort,然後用 string 當作 key,就不會有重複的問題。
Source