Check Distances Between Same Letters

Check Distances Between Same Letters

You are given a 0-indexed string s consisting of only lowercase English letters, where each letter in s appears exactly twice. You are also given a 0-indexed integer array distance of length 26.

Each letter in the alphabet is numbered from 0 to 25 (i.e. 'a' -> 0, 'b' -> 1, 'c' -> 2, ... , 'z' -> 25).

In a well-spaced string, the number of letters between the two occurrences of the i<sup>th</sup> letter is distance[i]. If the i<sup>th</sup> letter does not appear in s, then distance[i] can be ignored.

Return true if s is a well-spaced string, otherwise return false.

LeetCode Problem - 2399

class Solution {
    // Method to check if the distances between characters in a string match the given array
    public boolean checkDistances(String s, int[] distance) {
        // Create a HashMap to store the distances corresponding to characters
        Map<Character, Integer> charDistanceMap = new HashMap<>();

        // Initialize a character to start from 'a'
        char check = 'a';

        // Populate the HashMap with distances for each character
        for (int e : distance) {
            charDistanceMap.put(check, e);
            check++;
        }

        // Iterate over the string
        for (int i = 0; i < s.length(); i++) {
            // Get the first character
            char firstChar = s.charAt(i);
            // Iterate over the remaining characters
            for (int j = i + 1; j < s.length(); j++) {
                // Get the second character
                char secondChar = s.charAt(j);
                // If the characters are equal but the distance between them doesn't match the expected distance
                if ((firstChar == secondChar) && ((j - i - 1) != charDistanceMap.get(firstChar))) {
                    // Return false
                    return false;
                }
            }
        }
        // If all distances match, return true
        return true;
    }
}

Did you find this article valuable?

Support Gulshan Kumar by becoming a sponsor. Any amount is appreciated!