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","tan"],
  ["bat"]
]

一刷
题解:
思路很简单,遍历字符串数组,将字符串变为char array, 然后sort, 变成统一的字符串,然后判断map中是否存在该字符串。这里要注意几个字符串和char array互相转换的函数

Time Complexity - O(n * mlogm) , Space Complexity - O(m * n), m为字符串的平均长度

public class Solution {
    public List> groupAnagrams(String[] strs) {
        List> res = new ArrayList<>();
        if (strs == null) return res;
        Map> map = new HashMap<>();
        for(String s:strs){
            char[] sArr = s.toCharArray();
            Arrays.sort(sArr);
            String key = String.valueOf(sArr);
            if(!map.containsKey(key)) map.put(key, new ArrayList());
            map.get(key).add(s);
        }
        
        return new ArrayList<>(map.values());
    }
}

你可能感兴趣的:(49. Group Anagrams)