Description
Given an array of strings, group anagrams together.
Example:
1 | Input: ["eat", "tea", "tan", "ate", "nat", "bat"], |
Note:
- All inputs will be in lowercase.
- The order of your output does not matter.
解法
看到这个题,第一时间想到的就是采用哈希的方法,因为同类字符串的字母组成是相同的,那么如何哈希呢?思路是:先统计一个字符串里含各个字符的个数(第一次哈希,用一个长度为26的int数组统计对应字母的个数),再将这个int数组转化为字母字符串(这一步可以把字母组成相同的字符串转化为一样的字符串),再建立哈希表(第二次哈希),key为字母组成字符串(就是上一步生成的字符串),value为list,list中存组成相同的字符串。
具体代码如下:
1 | class Solution { |