两个题目的解法都在Solution类里面
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
ArrayList<List<String>> ret = new ArrayList<>();
for (int i = 0; i < strs.length; i++) {
for (int j = 0; j <= ret.size(); j++) {
if (ret.size() > j && !ret.get(j).isEmpty() && isAnagram(strs[i], ret.get(j).get(0))) {
ret.get(j).add(strs[i]);
break;
} else if (ret.size() == j) {
ArrayList<String> strings = new ArrayList<>();
strings.add(strs[i]);
ret.add(strings);
break;
}
}
}
return ret;
}
private boolean isAnagram(String s, String t) {
if (s.length() != t.length()) return false;
HashMap<Character, Integer> map1 = new HashMap<>();
for (int i = 0; i < s.length(); i++) {
if (map1.containsKey(s.charAt(i))) {
map1.put(s.charAt(i), map1.get(s.charAt(i)) + 1);
} else {
map1.put(s.charAt(i), 1);
}
}
for (int i = 0; i < t.length(); i++) {
if (map1.containsKey(t.charAt(i))) {
map1.put(t.charAt(i), map1.get(t.charAt(i)) - 1);
if (map1.get(t.charAt(i)) == 0) {
map1.remove(t.charAt(i));
}
} else {
return false;
}
}
return map1.isEmpty();
}
}