Perfect getKey JAVA beat 70%


  • 0
    D
    public List<List<String>> groupAnagrams(String[] strs) {
        List<List<String>> res = new ArrayList<>();
        HashMap<String,ArrayList<String>> map = new HashMap<>();
        for(String c :strs){
            String key = getKey(c);
            if(!map.containsKey(key)){
                map.put(key,new ArrayList<String>());
            }
            map.get(key).add(c);
        }
        for(String s : map.keySet()){
            res.add(map.get(s));
        }
        return res;
    }
    
    public String getKey(String a){
        String key = "";
        int [] times = new int[26];
        for(int i =0;i<a.length();i++){
            times[a.charAt(i)-'a']++;
        }
        for(int i =0;i<26;i++){
            if(times[i]!=0){
                key = key + times[i] + (char)(i+'a');
            }
        }
        return key;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.