Description:
Given an array of strings, group anagrams together.
Example:
Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
Output:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]
Note:
- All inputs will be in lowercase.
- The order of your output does not matter.
题意:给定一个字符串数组,将里面的字符串分类,如果两个字符串属于同一个类,那么一定满足这两个字符串有相同的长度和相同的字符(字符的排列顺序可以不同);
解法:我们想要判断两个字符串是否是同一类,首先我们需要对这两个字符串进行排序后比较;其次,需要使用哈希表来存储每次排完序的字符串,哈希表是以排序后的字符串及其在返回结果List列表中的下标作为键值对;这样,我们每次只需要判断排序后的字符串是否在哈希表中:如果在,取出键所对应的值即是List列表中的位置;如果不在,那么我们直接在List列表后插入一个新的包含次字符串的序列即可;
Java
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
List<List<String>> result = new ArrayList<>();
Map<String, Integer> strIndex = new HashMap<>();
int len = 0;
for (String str: strs) {
String tempStr = orderStr(str);
int index = strIndex.getOrDefault(tempStr, -1) == -1 ?
len : strIndex.get(tempStr);
if (index == len) {
List<String> temp = new ArrayList<>();
temp.add(str);
result.add(new ArrayList<>(temp));
} else {
result.get(index).add(str);
}
len = index == len ? len + 1 : len;
strIndex.put(tempStr, index);
}
return result;
}
private String orderStr(String s) {
StringBuilder result = new StringBuilder();
char[] str = s.toCharArray();
Arrays.sort(str);
for (char c: str) {
result.append(c);
}
return result.toString();
}
}