[LeetCode] Check Distances Between Same Letters

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 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 ith letter is distance[i]. If the ith letter does not appear in s, then distance[i] can be ignored.

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
bool checkDistances(string s, vector<int>& distance) {
unordered_map<char,int> freq;
for(int i = 0; i < s.length(); i++) {
int idx = s[i] - 'a';
if(freq.count(s[i])) {
int dis = i - freq[s[i]] - 1;
if(distance[idx] != dis) return false;
distance[idx] = -1;
} else freq[s[i]] = i;
}
for(auto& [k,_] : freq) {
int idx = k - 'a';
if(distance[idx] != -1) return false;
}
return true;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/09/04/PS/LeetCode/check-distances-between-same-letters/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.