LeetCode-49 Group Anagrams

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_36783389/article/details/83210966

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来实现这个功能

solution:

class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {
       Map<String,List<String>> map = new HashMap<>();
        for(String s : strs){
            char[] chars = s.toCharArray();
            Arrays.sort(chars);
            String new_str = new String(chars);
            if(map.get(new_str) == null){
                map.put(new_str,new ArrayList<>());
                map.get(new_str).add(s);
            }else{
                map.get(new_str).add(s);
            }
        }
        return new ArrayList<List<String>>(map.values()); 
        //这里的返回值类型是一个技巧,我第一次过的时候写的是遍历map集合给lists(最后要返回的List<List<String>>类型对象)赋值,然后过了后看大佬们都是直接return new ArrayList<List<String>>(map.values()) 的 发现自己还是太捞了,,
    }
}

猜你喜欢

转载自blog.csdn.net/qq_36783389/article/details/83210966