[LeetCode] Find Special Substring of Length K

3456. Find Special Substring of Length K

You are given a string s and an integer k.

Determine if there exists a substring of length exactly k in s that satisfies the following conditions:

  1. The substring consists of only one distinct character (e.g., "aaa" or "bbb").
  2. If there is a character immediately before the substring, it must be different from the character in the substring.
  3. If there is a character immediately after the substring, it must also be different from the character in the substring.

Return true if such a substring exists. Otherwise, return false.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
bool hasSpecialSubstring(string s, int k) {
int n = s.length();
for(int i = 1, cnt = 1; i < n; i++) {
if(s[i] == s[i-1]) ++cnt;
else {
if(cnt == k) return true;
cnt = 1;
}
if(i + 1 == n and cnt == k) return true;
}
return n == 1;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2025/02/16/PS/LeetCode/find-special-substring-of-length-k/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.