Fast Java solution (beats 88%, 5ms)


  • 0
    J
    public class Solution {
        public List<List<String>> groupStrings(String[] strings) {
            List<List<String>> output = new ArrayList<>();
            Map<String, List<String>> map = new HashMap<>();
            for (String s : strings) {
                String norm = normalize(s);
                List<String> list = map.get(norm);
                if (list == null) {
                    list = new ArrayList<>();
                    map.put(norm, list);
                }
                list.add(s);
            }
            for (List<String> list : map.values()) {
                Collections.sort(list);
                output.add(list);
            }
            return output;
        }
        
        String normalize(String s) {
            char[] C = s.toCharArray();
            int origin = 'a';
            int step = 'a' - C[0] + 26; // + 26 to make sure step > 0
            for (int i = 0; i < C.length; i++) {
                C[i] = (char)(((C[i] - origin + step) % 26) + origin);
            }
            return new String(C);
        }
    }

Log in to reply
 

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