Java Solution using HashMap


  • 0
    D
    public class Solution {
        public List<List<String>> groupStrings(String[] strings) {
            List<List<String>> result = new ArrayList<>();
            HashMap<String,List<String>> map = new HashMap<>();
            for (int i =0; i<strings.length;i++) {
                StringBuilder sb = new StringBuilder();
                for(int j = 0; j < strings[i].length(); j++) {
                    sb.append(Integer.toString( (strings[i].charAt(j) - strings[i].charAt(0) + 26 ) % 26 ));
                    sb.append(" ");
                }
                String s = sb.toString();
                if (map.containsKey(s)) {
                    map.get(s).add(strings[i]);
                }
                else {
                    List<String> l = new ArrayList<>();
                    l.add(strings[i]);
                    map.put(s,l);
                }
             }
             for (String s:map.keySet()) {
                 Collections.sort(map.get(s));
                 result.add(map.get(s));
             }
             return result;
    
        }
    }

Log in to reply
 

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