Java solution for corner case 'ba' using plus 26 mode 26


  • 0
    X

    I use the distance between chars of the string as the hashmap's key.
    For exampe:
    String "abc", the distances bewteen char 'a', 'b', 'c' is "11":
    'b' - 'a' = 1
    'c' - 'b' = 1.
    For "bcd", we have same distance "11".

    For case "az", the distance is "25"
    But for "ba", we cannot just use the method above.
    I enhance the method to calculate the distance between chars by adding 26 and then % 26:
    (('b' - 'a') + 26) % 26 = 25;
    This method can apply all cases.

    '''

    public List<List<String>> groupStrings(String[] strings) {
        List<List<String>> result = new ArrayList<>();
        HashMap<String, List<String>> map = new HashMap<>();
        
        for (String str : strings){
            String key = "";
            for (int i = 1; i < str.length(); i++){
                key += (str.charAt(i) - str.charAt(i- 1) + 26) % 26 + "";
            }
            if (map.containsKey(key)){
                map.get(key).add(str);
            } else {
                List<String> list = new ArrayList<>();
                list.add(str);
                map.put(key, list);
            }
        }
        
        for (Map.Entry<String, List<String>> entry : map.entrySet()){
            List<String> list = entry.getValue();
            result.add(list);
        }
        return result;
    }
    

    ''''


Log in to reply
 

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