49-字母异位词分组

 思路:

方法一:排序数组分类
思路

当且仅当它们的排序字符串相等时,两个字符串是字母异位词。

算法

维护一个映射 ans : {String -> List},其中每个键 ext{K}K 是一个排序字符串,每个值是初始输入的字符串列表,排序后等于 ext{K}K。

在 Java 中,我们将键存储为字符串,例如,code。 在 Python 中,我们将键存储为散列化元组,例如,('c', 'o', 'd', 'e')。

思路连接:https://leetcode-cn.com/problems/group-anagrams/solution/zi-mu-yi-wei-ci-fen-zu-by-leetcode/

这里我只用了一种思路

class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {
        if (strs.length == 0) return new ArrayList();
         List<List<String>> res=new ArrayList<>();
         Map<String,List> map=new HashMap<>();
        for(String s:strs)
        {
            char[] c=s.toCharArray();//String转换为字符串数组
            Arrays.sort(c);//对字符数组进行排序
            String key=String.valueOf(c);//排序后的字符串数组转化为String,当做key
            if(!map.containsKey(key)) //如果不存在这个key,就新建一个键-值对
            {
                map.put(key,new ArrayList<>());
            }
            map.get(key).add(s);//获得这个key的value,也就是List,之后List里面加入当前的String字符串s

        }
         return new ArrayList(map.values());//注意一下,我没想到,map.values()作用是获得所有value值
} 
}

 总结:重点是这个思路,HashMap,以及

 Arrays.sort(c);
char[] c=s.toCharArray();
 String key=String.valueOf(c);

以及HashMap的get,put方法
可以看我转载的这个:https://www.cnblogs.com/lzh1043060917/p/12799801.html
原文地址:https://www.cnblogs.com/lzh1043060917/p/12799914.html