Leetcode 2399. 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 also have a 0-indexed integer array distance
of length 26.
Each letter in the alphabet is numbered from 0 to 25 (i.e., ‘a’ is 0, ‘b’ is 1, …, ‘z’ is 25).
In a well-spaced string, the distance between the two occurrences of the i-th letter is distance[i]. If the letter i does not appear in s
, then distance[i]
can be ignored.
Return true
if all the letters in s
are well-spaced according to distance, otherwise return false
.
Input:
s = "abaccb"
distance = [1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
Output: true
Input:
s = "aa"
distance = [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
Output: false
s
has even length between 2 and 52 (inclusive).distance[i]
is a non-negative integer less than 50.first_occurrences
of length 26 to store the index of the first occurrence of each character.s
:
distance
array.false
.true
.#include <vector>
#include <string>
using namespace std;
bool checkDistances(string s, vector<int>& distance) {
vector<int> first_occurrences(26, -1);
for (int i = 0; i < s.length(); ++i) {
int idx = s[i] - 'a';
if (first_occurrences[idx] == -1) {
first_occurrences[idx] = i;
} else {
int required_distance = distance[idx];
int actual_distance = i - first_occurrences[idx] - 1;
if (required_distance != actual_distance) {
return false;
}
}
}
return true;
}
s
. We traverse the string once and perform constant-time operations.first_occurrences
array always requires the same amount of space.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?