【题目描述】
给你一个字符串数组,请你将 字母异位词 组合在一起。可以按任意顺序返回结果列表。
字母异位词 是由重新排列源单词的字母得到的一个新单词,所有源单词中的字母通常恰好只用一次。
https://leetcode.cn/problems/group-anagrams/?favorite=2cktkvj
【示例】
import java.util.*;
import java.util.stream.Collectors;
// 2022-12-19
class Solution {
List<List<String>> res = new ArrayList<>();
public List<List<String>> groupAnagrams(String[] strs) {
// "eat","tea","tan","ate","nat","bat"
List<String> strings = Arrays.asList(strs);
int[] dp = new int[strings.size()];
for (String x : strs){
List<String> list1 = fullStr(x);
List<String> list = new ArrayList<>();
Set<String> set = new HashSet<>();
for (int i = 0, len = strings.size(); i < len; i++) {
String tmp = strings.get(i);
if (list1.contains(tmp) && dp[i] == 0){
set.add(tmp);
dp[i] = 1;
}
}
// System.out.println("set: " + set);
for (String xx: set){
if (xx.length() != 0){
list.add(xx);
}
}
System.out.println(list);
res.add(list);
}
return res;
}
public List<String> fullStr(String x) {
List<String> list = new ArrayList<>();
list.add(x.charAt(0)+"");
for (int i = 1; i < x.length(); i++){
char c = x.charAt(i);
List<String> list2 = new ArrayList<>();
for (String s : list){
list2.add(s+c); // eat
list2.add(c+s); // tea
for (int j = 1; j < s.length(); j++){ // e + t + a
String tmp = s.substring(0, j) + c + s.substring(j);
list2.add(tmp);
}
}
list = list2;
}
// System.out.println(list);
return list;
}
}
public class Main{
public static void main(String[] args) {
String[] str = {"eat","tea","tan","ate","nat","bat"};
new Solution().groupAnagrams(str); // 输出: 3 [1, 5], [1, 4], [1]
// new Solution().fullStr("eat");
}
}