字母异位词分组
给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。
示例:
输入: ["eat", "tea", "tan", "ate", "nat", "bat"],
输出:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]
思路+代码+注释:
public class FourNineSuccess {
public static List<List<String>> groupAnagrams(String[] strs) {
/*
思路:
1. 对字符串数组中每个字符串按字符大小进行排序
2. 排序后的字符串数组,如果字符串相同证明是异位词,那么将排序后的字符串作为key,
value为HashSet将原字符串存到Set中—使用Set的目的是去重,避免有相同的串
3. 遍历Map中的value,将所有value对应的Set存到结果集合中
注意点:空串与空串算作异位词
这道题有个问题,就是相同的字符串也当作异位词,个人认为不应该
*/
HashMap<String, ArrayList> hashMap = new HashMap<>();
for (int i = 0; i < strs.length; i++) {
//tmp保存当前字符串,因为后面会对该字符串进行排序改变内容
String tmp = xuanZeSort(strs[i]);
if (hashMap.containsKey(tmp)) {
ArrayList set = hashMap.get(tmp);
set.add(strs[i]);
} else {
ArrayList set = new ArrayList<>();
set.add(strs[i]);
hashMap.put(tmp, set);
}
}
List<List<String>> result = new ArrayList<List<String>>(hashMap.keySet().size());
List<ArrayList> values=new ArrayList<>(hashMap.values());
for (ArrayList value : values
) {
result.add(value);
}
return result;
}
public static String xuanZeSort(String str) {
char[] chs = str.toCharArray();
for (int i = 0; i < chs.length - 1; i++) {
for (int j = i + 1; j < chs.length; j++) {
if (chs[j] < chs[i]) {
char temp = chs[j];
chs[j] = chs[i];
chs[i] = temp;
}
}
}
return new String(chs);
}
}