Share my 3ms java solution


  • 2
    V
    public List<List<String>> groupStrings(String[] strings) {
        Map<String, List<String>> map = new HashMap<> ();
        for (String str : strings) {
            String key = getKey(str);
            if (map.containsKey(key)) {
                map.get(key).add(str);
            } else {
                List<String> list = new ArrayList<> ();
                list.add(str);
                map.put(key, list);
            }
        }
        return new ArrayList<List<String>> (map.values());
    }
    
    private String getKey(String word) {
        StringBuilder sb = new StringBuilder();
        if (word.isEmpty())
            return sb.toString();
        char ch = word.charAt(0);
        for (int i = 0; i < word.length(); i++) {
            sb.append((char)((word.charAt(i) + 26 - ch) % 26));
        }
        return sb.toString();
    }

Log in to reply
 

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