题目:
给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。
示例:
输入: ["eat", "tea", "tan", "ate", "nat", "bat"]
输出:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]
代码:
public class Test18 {
@Test
public void test(){
String[] test =new String[]{"",""};
List<List<String>> lists = new Test18().groupAnagrams(test);
for (List<String> list : lists) {
System.out.println("list = " + list);
}
}
public List<List<String>> groupAnagrams(String[] strs) {
List<String> strings = Arrays.asList(strs);
List<List<String>> result = new ArrayList<>();
function(result,new ArrayList<>(strings));
return result;
}
public void function(List<List<String>> result,List<String> strings){
if (strings.size()==0) {
return;
}
if (strings.size()==1) {
result.add(strings);
return;
}
List<String> temp = new ArrayList<>();
temp.add(strings.get(0));
char[] chars = strings.get(0).toCharArray();
strings.remove(0);
if (chars.length==0) {
for (int i = 0; i < strings.size(); i++) {
if (strings.get(i)=="") {
temp.add(strings.remove(i));
}
}
}else{
List<Character> temp1 = new ArrayList<>();
for (char aChar : chars) {
temp1.add(aChar);
}
for (int i = 0; i < strings.size(); i++) {
List<Character> temp2 = new ArrayList<>();
for (char aChar : strings.get(i).toCharArray()) {
temp2.add(aChar);
}
if (temp1.containsAll(temp2) && !temp.contains(strings.get(i))) {
temp.add(strings.get(i));
strings.remove(i);
}
}
}
result.add(temp);
function(result,strings);
}
}