Check Distances Between Same Letters
This problem can be solved by keeping track of the first occurrence of each letter in a dictionary. Then, when we encounter the second occurrence of the letter, we can check if the distance between the two occurrences matches the distance in the given distance list. The indices of the alphabet can be calculated by subtracting the ASCII value of ‘a’ from the current character’s ASCII value.
Python solution:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
| class Solution:
def checkDistances(self, s: str, distance: List[int]) -> bool:
# Initialize a dictionary to store the first occurrence of each letter
first_occurrence = {}
# Iterate over the string
for i, letter in enumerate(s):
# If the letter has been seen before
if letter in first_occurrence:
# Calculate the index of the letter in the alphabet
index = ord(letter) - ord('a')
# If the distance between the current index and the first occurrence does not match the given distance, return False
if i - first_occurrence[letter] - 1 != distance[index]:
return False
else:
# If the letter has not been seen before, store its index
first_occurrence[letter] = i
# If all distances match, return True
return True
|
This code iterates over the string and checks for each letter whether the number of characters between its two occurrences matches the given distance. The use of a dictionary allows for quick access to the first occurrence of each letter, ensuring that the solution is efficient.