My concise java solution with explanation


  • 0
    W

    //regular: if the afterword is bigger than forward , just minus. Otherwise +26 then minus. But don't forget to add 'a', because the shift maybe more than 9, so how can we use one character represent the shift? use the alphabet itself !

    public List<List<String>> groupStrings(String[] strings) {
    List<List<String>> ret = new ArrayList<>();
    if(strings == null || strings.length < 1) return ret;
    Map<String, List<String>> map = new HashMap<>();
    for(String str : strings) {
    char ch[] = str.toCharArray();
    String regular = " "; // one char regular is " " (one space)
    for(int i = 1; i < ch.length; i++) {
    int shift = ch[i] - ch[i-1];
    shift = (shift >= 0) ? shift : shift+26;
    regular += (char)('a' + shift);
    }
    List<String> value = (List<String>)map.get(regular);
    if(value == null) {
    value = new ArrayList<>();
    }
    value.add(str);
    map.put(regular, value);
    }

        return new ArrayList<>(map.values());
    }

Log in to reply
 

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