LeetCode 49. Group Anagrams (Medium)

题目

Given an array of strings strs, group the anagrams together. You can return the answer in any order.
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
 
Example 1:

Input: strs = ["eat","tea","tan","ate","nat","bat"]
Output: [["bat"],["nat","tan"],["ate","eat","tea"]]

Example 2:

Input: strs = [""]
Output: [[""]]

Example 3:

Input: strs = ["a"]
Output: [["a"]]

Constraints:

1 <= strs.length <= 104
0 <= strs[i].length <= 100
strs[i] consists of lowercase English letters.

思路

方法1 (Java)

利用HashMap,将字符串内的字符排序,作为key,则同一组相同字母异序词则会有相同的key,Map的value为相同字母异序词的list。

class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {
        Map<String, List<String>> map = new HashMap<>();
        for(int i = 0; i < strs.length; i++){
            char[] charArr = strs[i].toCharArray();
            Arrays.sort(charArr);
            String str = new String(charArr);
            if(!map.containsKey(str)) map.put(str, new ArrayList<String>());
            map.get(str).add(strs[i]);
        }
        List<List<String>> res = new ArrayList<>();
        for(String key : map.keySet()){
            res.add(map.get(key));
        }
        return res;
    }
}

 

方法2 (Java)

不利用排序方法,对每个字符串使用一个char[],记录26个字母出现次数,并生成字母+出现次数的字符串作为key。
"eat""ate"的key都是"a1e1t1"

class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {
        Map<String, List<String>> map = new HashMap<>();
        List<List<String>> res = new ArrayList<>();
        
        for(String str : strs){
            int[] charCount = new int[26];
            for(int i = 0; i < str.length(); i++){
                char ch = str.charAt(i);
                charCount[ch-'a']++;
            }
            String key = "";
            for(int i = 0; i < 26; i++){
                if(charCount[i] == 0) continue;
                char ch = (char)(i+'a');
                key += String.valueOf(ch)+charCount[i];
            }
            if(!map.containsKey(key)) map.put(key, new ArrayList<>());
            map.get(key).add(str);
        }
        
        for(String str : map.keySet()){
            res.add(map.get(str));
        }
        return res;
    }
}
posted @ 2021-12-16 11:33  红鲤鱼绿鲤鱼与阿米娅  阅读(45)  评论(0)    收藏  举报