题目在注释里,直接看有点乱,先说说大体思路:
就是将每个字符串遍历一遍再存到set中,如果装结果的map中有一样的set,则认为已经遇到过一样的字母的字符串,然后通以set作为key从map中拿到装索引值的list,将索引值添加进去。遍历完了再通过
List< HashSet< Character>> group拿到对应的索引再返回。
该解法不适合字符串中有重复字母的情况。。。时间复杂度算不出来>﹏<不过应该挺好。
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
/**
* no.49
* 给出一个字符串数组,将其索引可以通过颠倒顺序产生相同结果的单词进行分组
* 如["eat","tea","ate"],["nat","tan"],返回字符串数组组成的数组。
* 输入:["eat","nat","tea","tan","bat","ate"]
* @author 煎鱼
* map
*
* HashMap<HashSet<Character>, Integer> map = new HashMap<>();
HashSet<Character> set1 = new HashSet<>();
HashSet<Character> set2 = new HashSet<>();
set1.add('a');
set2.add('a');
set1.add('b');
set2.add('b');
map.put(set1, 1);
System.out.println(map.containsKey(set2));
返回true,证明set可以作为key
*/
public class Group_Anagrams {
public static List<List<String>> solution(String[] arr){
List<HashSet<Character>> group = new ArrayList<>();//装组合
HashMap<HashSet<Character>, List<Integer>> map = new HashMap<>();//所有数据
for(int i = 0; i<arr.length; i++) {
HashSet<Character> character = new HashSet<>();//记录
for(int j = 0; j < arr[i].length(); j++) {
character.add(arr[i].charAt(j));
}
if(map.containsKey(character)) {
List<Integer> index = map.get(character);//装set的索引
index.add(i);
map.put(character, index);
}else {
List<Integer> index = new ArrayList<Integer>();//装set的索引
index.add(i);
group.add(character);
map.put(character, index);
}
}
//返回
List<List<String>> res = new ArrayList<>();//结果
for(int i = 0; i < group.size(); i++) {
List<Integer> index = map.get(group.get(i));//结果索引
List<String> g = new ArrayList<>();//装字符串
for(int j = 0; j < index.size(); j++) {
g.add(arr[index.get(j)]);
}
res.add(g);
}
return res;
}
public static void main(String[] args) {
String[] arr = new String[] {"eat","nat","tea","tan","bat","ate"};
System.out.println(solution(arr).toString());
}
}
返回: [[eat, tea, ate], [nat, tan], [bat]]