Leetcode Problem 2399. Check Distances Between Same Letters

2399. Check Distances Between Same Letters

Leetcode Solutions

Tracking First Occurrences and Verifying Distances

  1. Initialize an array first_occurrences of length 26 with default values of -1, to store the first occurrence index of each character.
  2. Iterate through each character c in the string s using its index i.
  3. Convert the character c to its corresponding index in the alphabet (0 for 'a', 1 for 'b', etc.) by subtracting 'a' from it.
  4. If first_occurrences at the character's index is -1, store i as the first occurrence.
  5. Otherwise, calculate the distance between i and the stored first occurrence, and compare it to the expected distance from the distance array.
  6. If the calculated distance does not match the expected distance, return false.
  7. If all characters match their expected distances, return true after the loop.
UML Thumbnail

Using a Dictionary to Track Character Indices

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...