Java 2ms Beats 99%


  • 0
        public List<List<String>> groupStrings(String[] strings) {
            Map<String, Integer> reductionToIndex = new HashMap<String, Integer>();
            List<List<String>> res = new ArrayList<List<String>>();
            int curIndex = 0;
            for (int i=0;i<strings.length;i++) {
                String reducedString = reduction(strings[i]);
                Integer index = reductionToIndex.get(reducedString);
                if (index == null) {
                    res.add(new ArrayList<String>());
                    res.get(curIndex).add(strings[i]);
                    reductionToIndex.put(reducedString, curIndex);
                    curIndex++;
                }
                else res.get(index).add(strings[i]);
            }
            return res;
        }
        
        public String reduction(String input) {
            int diff = input.charAt(0) - 'a';
            if (diff == 0) {return input;}
            char[] reduction = input.toCharArray();
            for (int i=0;i<input.length();i++){ 
                char reducedChar = (char) (reduction[i] - diff);
                reduction[i] = reducedChar >= 'a' ? reducedChar : (char) ('z' + 1 - 'a' + reducedChar);
            }
            return new String(reduction);
        }
    

Log in to reply
 

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