32.Group Anagrams(相同元素的不同组合)

Level:

  Medium

题目描述:

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.

思路分析:

  解法一:求相同元素的不同组合,解题思路是,给不同的字母赋不同的值,那么如果是由相同元素组成的字符串,那么字符串中每个元素相乘最后的乘积是相同的,用map保存,遇到值相同的放到同一个列表。

  解法二:使用一个长度为26的数组,来记录每个字符串中字符出现的频率,如果两个字符串的组成元素相同,那么遍历两个字符串,更新后的长度为26的数组是相同的。和解法一一样同样用map保存遍历过程中的结果。

代码

public class Solution{
    public List<List<String>>groupAnagrams(String []strs){
        List<List<String>>res=new ArrayList<>();
        List<String>list;
        if(strs==null||strs.length==0)
            return res;
        int []prim={2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103}; //都为素数,防止出现不同元素的乘积也相同
        HashMap<Integer,Integer>map=new HashMap<>();
        for(String str:strs){
            int k=1;
            for(int i=0;i<str.length();i++){
                k=k*prim[str.charAt(i)-'a'];
            }
            if(map.containsKey(k)){
                list=res.get(map.get(k));//如果map中包含该值,取出该值对应字符串所在的列表
            }else{
                list=new ArrayList<>(); //如果map中不包含该值,新建一个该值对应的列表
                res.add(list);
                map.put(k,res.size()-1); //map中存放的是乘积值和其序列在res中的位置。
            }
            list.add(str);//将当前字符串加入取出的列表
        }
        return res;
    }
}
public class Solution{
    public List<List<String>> groupAnagrams(String[] strs){
        HashMap<String,List<String>>map=new HashMap<>();
        List<String>list;
        for(String str:strs){
            int[] arr=new int[26];//统计字符串中每个字符出现的次数
                for(int i=0;i<str.length();i++){
                    arr[str.charAt(i)-'a']++;
                }
            String key=Arrays.toString(arr);
            if(map.containsKey(key)){
                list=map.get(key);
            }else{
                list=new ArrayList<>();
            }
            list.add(str);
            map.put(key,list);
        }
        return new ArrayList<>(map.values());
    }
}

猜你喜欢

转载自www.cnblogs.com/yjxyy/p/10846985.html