49

import java.util.*;

/**
 * create a map 
 *     key is #0#4#1#7... 26 total
 *     value is these strings
 *     hint: calculate times of per character and then compare them
 */
class Solution{
    public List> groupAnagrams(String[] strs){
        if(strs.length == 0){
            return new ArrayList();
        }
        Map res = new HashMap();
        int[] count = new int[26];
        for(String s : strs){
            Arrays.fill(count,0);
            for(char c : s.toCharArray()){
                count[c - 'a']++;
            }

            StringBuilder sb = new StringBuilder("");
            for(int i = 0; i < 26; i++){
                sb.append('#');
                sb.append(count[i]);
            }
            String key = sb.toString();
            if(!res.containsKey(key)){
                res.put(key,new ArrayList());
            }
            res.get(key).add(s);
        }
        return new ArrayList(res.values());
    }
}

 

转载于:https://www.cnblogs.com/zhaijiayu/p/11541578.html

你可能感兴趣的:(java)