5 ms Java solution


  • 0
    W
    public class Solution {
        public List<List<String>> groupStrings(String[] strings) {
            List<List<String>> res = new ArrayList<>();
            if (strings.length == 0) return res;
            Map<String, List<String>> map = new HashMap<>();
            for (String s: strings) {
                String k = getKey(s);
                if (!map.containsKey(k))
                    map.put(k, new ArrayList<>());
                map.get(k).add(s);
            }
            for (String k: map.keySet()) {
                Collections.sort(map.get(k));
                res.add(map.get(k));
            }
            return res;
        }
        
        private String getKey(String s) {
            StringBuilder sb  = new StringBuilder();
            int diff = (int)('a' - s.charAt(0));
            for (int i=1; i<s.length(); i++) {
                char c = s.charAt(i);
                sb.append((char)((int)(c+diff-'a'+26)%26 + 'a'));
            }
            return sb.toString();
        }
    }

Log in to reply
 

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