Simple Java


  • 0
    S
    public class Solution {
        public List<List<String>> groupStrings(String[] strings) {
            Map<String, List<String>> map = getMap(strings);
            return getList(map);
        }
        
        private Map<String, List<String>> getMap(String[] strings) {
            Map<String, List<String>> map = new HashMap<>();
            for (String str : strings) {
                String key = getDiff(str);
                if (!map.containsKey(key)) {
                    List<String> list = new ArrayList<String>();
                    map.put(key, list);
                }
                map.get(key).add(str);
            }
            
            return map;
        }
        
        private List<List<String>> getList(Map<String, List<String>> map) {
            List<List<String>> result = new ArrayList<List<String>>();
            List<String> keys = new ArrayList<String>(map.keySet());
            for(String cur: keys) {
                result.add(map.get(cur));
            }
            return result;
        }
        
        private String getDiff(String str) {
            String key = "";
            for (int i = 0; i < str.length()-1; i++) {
                int c = (str.charAt(i) - str.charAt(i+1));
                key += c < 0 ? (char)(c + 26) : (char)c;
            }
            return key.length() == 0 ? "a" : key;
        }
    }

Log in to reply
 

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