给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。
示例:
输入: [“eat”, “tea”, “tan”, “ate”, “nat”, “bat”]
输出:
[
[“ate”,“eat”,“tea”],
[“nat”,“tan”],
[“bat”]
]
说明:
所有输入均为小写字母。
不考虑答案输出的顺序。
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
List<List<String>> lists = new ArrayList<>();
int[][] ints = new int[strs.length][27];
int[] index = new int[strs.length];
loop:
for (int i = 0; i < strs.length; i++) {
ints[i][0] = strs[i].length();
for (int j = 0; j < strs[i].length(); j++) {
ints[i][(strs[i].charAt(j))-96]++;
}
for (int j = 0; j < i; j++) {
if (j != 0 && index[j] == 0) {
continue;
}
if (Arrays.equals(ints[j], ints[i])) {
lists.get(index[j]).add(strs[i]);
continue loop;
}
}
lists.add(new ArrayList<>());
index[i] = lists.size() - 1;
lists.get(index[i]).add(strs[i]);
}
return lists;
}
}