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.
题意就是根据相同字符组成的字符串进行一个归类:
方法一:对数组进行遍历 找出相同组的数据 并使得该位置的数据为null 遍历不同组的数据
public List<List<String>> groupAnagrams(String[] strs) {
List<List<String>> res = new ArrayList<>();
for (int i = 0; i < strs.length; i++) {
List<String> tmp = new ArrayList<>();
String tmpValue = strs[i];
if (tmpValue!=null) {
tmp.add(tmpValue);
for (int j = i + 1; j < strs.length; j++) {
if (strs[j] !=null && isGroup(tmpValue, strs[j])) {
tmp.add(strs[j]);
strs[j] = null;
}
}
res.add(tmp);
}
}
return res;
}
public boolean isGroup(String a,String b) {
if(a== null || b== null) {
return false;
}
if(a.equals(b)) {
return true;
}
if(a.length() == b.length()) {
char [] as= a.toCharArray();
char [] bs = b.toCharArray();
Arrays.sort(as);
Arrays.sort(bs);
for(int index=0;index<a.length();index++) {
if(as[index] != bs[index]) {
return false;
}
}
return true;
}
return false;
}
方法二: 调用map 对每个数据进行获取一个key 该key为排序后的值
public List<List<String>> groupAnagramsBetter(String[] strs) {
if (strs.length == 0) return new ArrayList<>();
Map<String, List<String>> ans = new HashMap<>();
for (String s : strs) {
char[] ca = s.toCharArray();
Arrays.sort(ca);
String key = String.valueOf(ca);
if (!ans.containsKey(key)) ans.put(key, new ArrayList<>());
ans.get(key).add(s);
}
return new ArrayList<>(ans.values());
}