package a2;
import a2.Solution;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
/*
* 只用比较字符串的各个字母个数就行
**/
class Solution {
public static void main(String[] args) {
String[] str = {"eat","tea","tan","ate","nat","bat"};
System.out.println(new Solution().groupAnagrams(str));
}
public class Str {
int[] num = new int[26];
String s;
public Str(String s) {
this.s = s;
for (int i = 0; i < s.length(); i++) {
num[s.charAt(i) - 'a']++;
}
}
@Override
public boolean equals(Object object) {
if (this == object) return true;
if (object == null || getClass() != object.getClass()) return false;
Str str = (Str) object;
return Objects.deepEquals(num, str.num);
}
@Override
public int hashCode() {
return Objects.hash(Arrays.hashCode(num), s);
}
}
public List<List<String>> groupAnagrams(String[] strs) {
List<Str> res = new ArrayList<>();
for(String str : strs){
Str str1 = new Str(str);
res.add(str1);
}
int[] sign = new int[strs.length];
List<List<String>> ans = new ArrayList<>();
for (int i = 0; i < strs.length; i++) {
if(sign[i] == 0) {
List<String> list = new ArrayList<>();
sign[i] = 1;
list.add(res.get(i).s);
for (int j = i + 1; j < strs.length; j++) {
if(sign[j] == 0 && res.get(i).equals(res.get(j))){
sign[j] = 1;
list.add(res.get(j).s);
}
}
ans.add(list);
}
}
return ans;
}
}
package a2;
import a2.Solution2;
import java.util.*;
/*
* 对于对字母排序没有要求的情况,可以将所有字母排序后的结果作键
* 排序前的字符串作值
* */
class Solution2 {
public static void main(String[] args) {
String[] str = {"eat","tea","tan","ate","nat","bat"};
System.out.println(new Solution2().groupAnagrams(str));
}
public List<List<String>> groupAnagrams(String[] strs) {
HashMap<String, List<String>> map = new HashMap<>();
for(String str : strs) {
char[] charArray = str.toCharArray();
Arrays.sort(charArray);
String sorted = new String(charArray);
List<String> list = map.get(sorted);
if(list == null) {
list = new ArrayList<>();
}
list.add(str);
map.put(sorted, list);
}
return new ArrayList<>(map.values());
}
}