【Lintcode】772. Group Anagrams

題目地址:

https://www.lintcode.com/problem/group-anagrams/description

給定一個字符串數組,將其按照anagram分類返回。anagram意思是,字母相同並且每個字母出現次數也相同。

可以將每個字符串內的字符排序,這樣每個anagram內的字符串都會對應唯一的一個key,再用一個哈希表記錄每個key對應哪些字符串即可。代碼如下:

import java.util.*;

public class Solution {
    /**
     * @param strs: the given array of strings
     * @return: The anagrams which have been divided into groups
     */
    public List<List<String>> groupAnagrams(String[] strs) {
        // write your code here
        List<List<String>> res = new ArrayList<>();
        if (strs == null || strs.length == 0) {
            return res;
        }
        
        Map<String, List<String>> map = new HashMap<>();
        for (int i = 0; i < strs.length; i++) {
            char[] s = strs[i].toCharArray();
            Arrays.sort(s);
            String key = new String(s);
            
            map.putIfAbsent(key, new ArrayList<>());
            map.get(key).add(strs[i]);
        }
    
        for (Map.Entry<String, List<String>> entry : map.entrySet()) {
            res.add(entry.getValue());
        }
        
        return res;
    }
}

時間複雜度O(nllogl)O(nl\log l),空間O(nl)O(nl)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章