[leetcode]49. Group Anagrams重排列字符串分组

是之前的重排列字符串的延伸,判断是重排列后存到HashMap中进行分组

这种HashMap进行分组的方式很常用

public List<List<String>> groupAnagrams(String[] strs) {
        /*
        其实重排列的那个题是有两种做法的,之前整理的是比较好的的一种字母哈希表的方法,还有一种方法
        是把字符串排序,然后进行比较就行。
        这个题正好就是用了排序的方法,排序后的字符串作为key,list作为value就行
        一开始想用字母哈希表的方法,结果没做出来
        java中没有字符串排序方法,要自己实现
         */
        Map<String,List<String>> map = new HashMap<>();
        for (int i = 0; i < strs.length; i++) {
            String str  = strs[i];
            String temp = sort(str);
            List<String> list = map.getOrDefault(temp,new ArrayList<>());
            list.add(str);
            map.put(temp,list);
        }
        List<List<String>> res = new ArrayList<>();
        for (String str:
        map.keySet()){
            res.add(map.get(str));
        }
        return res;
    }
    public String sort(String str)
    {
        char[] chars = str.toCharArray();
        Arrays.sort(chars);
        return new String(chars);
    }

分组就要想到HashMap!!!!!!!!!!!

原文地址:https://www.cnblogs.com/stAr-1/p/8289200.html

时间: 2024-10-09 12:38:53

[leetcode]49. Group Anagrams重排列字符串分组的相关文章

Leetcode 49. Group Anagrams

Given an array of strings, group anagrams together. For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"], Return: [ ["ate", "eat","tea"], ["nat",

19.2.7 [LeetCode 49] Group Anagrams

Given an array of strings, group anagrams together. Example: Input: ["eat", "tea", "tan", "ate", "nat", "bat"], Output: [ ["ate","eat","tea"], ["nat","

LeetCode 49. Group Anagrams HashTable

Given an array of strings, group anagrams together. Example: Input: ["eat", "tea", "tan", "ate", "nat", "bat"], Output: [ ["ate","eat","tea"], ["nat","

[leetcode]49. Group Anagrams变位词归类

Given an array of strings, group anagrams together. Example: Input: ["eat", "tea", "tan", "ate", "nat", "bat"], Output: [ ["ate","eat","tea"], ["nat","

LeetCode开心刷题二十六天——49.Group Anagrams

49. Group Anagrams Medium 1824116FavoriteShare Given an array of strings, group anagrams together. Example: Input: ["eat", "tea", "tan", "ate", "nat", "bat"], Output: [ ["ate","eat

49. Group Anagrams(js)

49. Group Anagrams Given an array of strings, group anagrams together. Example: Input: ["eat", "tea", "tan", "ate", "nat", "bat"], Output: [ ["ate","eat","tea"], [&q

【LeetCode】49. Group Anagrams

Given an array of strings, group anagrams together. For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"], Return: [ ["ate", "eat","tea"], ["nat",

【一天一道LeetCode】#49. Group Anagrams

一天一道LeetCode系列 (一)题目 Given an array of strings, group anagrams together. For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"], Return: [ ["ate", "eat","tea"

【Leetcode】Group Anagrams

题目链接:https://leetcode.com/problems/anagrams/ 题目: Given an array of strings, group anagrams together. For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"], Return: [ ["ate", &q