代码+注释+思路:
public class FourNine {
public static void main(String[] args) {
groupAnagrams(new String[]{"eat", "tea", "tan", "ate", "nat", "bat"});
}
public static List<List<String>> groupAnagrams(String[] strs) {
/*
思路:
1. 对字符串数组中每个字符串按字符大小进行排序
2. 排序后的字符串数组,如果字符串相同证明是异位词,那么将排序后的字符串作为key,
value为HashSet将原字符串存到Set中—使用Set的目的是去重,避免有相同的串
3. 遍历Map中的value,将所有value对应的Set存到结果集合中
注意点:空串与空串算作异位词
这道题有个问题,就是相同的字符串也当作异位词,个人认为不应该
*/
HashMap<String, HashSet> hashMap = new HashMap<>();
for (int i = 0; i < strs.length; i++) {
//tmp保存当前字符串,因为后面会对该字符串进行排序改变内容
String tmp = xuanZeSort(strs[i]);
if (hashMap.containsKey(tmp)) {
HashSet set = hashMap.get(tmp);
set.add(strs[i]);
} else {
HashSet set = new HashSet<>();
set.add(strs[i]);
hashMap.put(tmp, set);
}
}
List<List<String>> result = new ArrayList<List<String>>(hashMap.keySet().size());
List<HashSet> values=new ArrayList<>(hashMap.values());
for (HashSet value : values
) {
//判断HashSet中是否有包含""的Set,如果有那么查找原数组中所有空串
if (value.contains(""))
{
List<String> kongChuanList=new ArrayList<>();
for (String s:strs
) {
if ("".equals(s))
{
kongChuanList.add("");
}
}
result.add(kongChuanList);
}else {
result.add(new ArrayList<String>(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);
}
}