4ms Java Solution Using HashMap


  • 0
    I
    public List<List<String>> groupStrings(String[] strings) {
        HashMap<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>();
        List<List<String>> result = new ArrayList<List<String>>();
        for (String s : strings){
            String temp = sort(s);
            if (map.containsKey(temp)){
                map.get(temp).add(s);
            }
            else {
                map.put(temp, new ArrayList<String>());
                map.get(temp).add(s);
            }
        }
        for (ArrayList<String> list : map.values()){
             result.add(list);
        }
        return result;
    }
    public String sort(String a ){
        int temp;
        if (a.length()==0){
            return "-0";       // if input string is "", map key will be "-0"
        }
        StringBuilder sb = new StringBuilder("");
        if (a.length()==1){
            return "-1";       // if input string only contain one letter, map key will be "-1"
        }
        for (int i = 1; i<a.length();i++){
            temp = a.charAt(i) - a.charAt(i-1);
            if (temp<0){
                temp +=26;
            }
            sb.append(temp).append(".");   // add "." to make sure the number of shifts is the same 
        }
        return sb.toString();
    }

Log in to reply
 

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