Input: s ="aaabaaa", k =3Output: trueExplanation:
The substring `s[4..6] == "aaa"` satisfies the conditions.* It has a length of 3.* All characters are the same.* The character before `"aaa"`is`'b'`, which is different from `'a'`.* There is no character after `"aaa"`.
We can use a sliding window of length k to check each substring. For each window, we check if all characters are the same, and if the characters before and after the window (if they exist) are different from the window character.
classSolution {
public:bool hasSpecialSubstring(string s, int k) {
int n = s.size();
for (int i =0; i + k <= n; ++i) {
char c = s[i];
bool ok = true;
for (int j =1; j < k; ++j) if (s[i+j] != c) { ok = false; break; }
if (!ok) continue;
if (i >0&& s[i-1] == c) continue;
if (i + k < n && s[i+k] == c) continue;
return true;
}
return false;
}
};
classSolution {
publicbooleanhasSpecialSubstring(String s, int k) {
int n = s.length();
for (int i = 0; i + k <= n; i++) {
char c = s.charAt(i);
boolean ok =true;
for (int j = 1; j < k; j++) if (s.charAt(i+j) != c) { ok =false; break; }
if (!ok) continue;
if (i > 0 && s.charAt(i-1) == c) continue;
if (i + k < n && s.charAt(i+k) == c) continue;
returntrue;
}
returnfalse;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
classSolution {
funhasSpecialSubstring(s: String, k: Int): Boolean {
val n = s.length
for (i in0..n-k) {
val c = s[i]
if ((1 until k).any { s[i+it] != c }) continueif (i > 0&& s[i-1] == c) continueif (i + k < n && s[i+k] == c) continuereturntrue }
returnfalse }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
classSolution:
defhasSpecialSubstring(self, s: str, k: int) -> bool:
n = len(s)
for i in range(n - k +1):
c = s[i]
if any(s[i+j] != c for j in range(k)):
continueif i >0and s[i-1] == c:
continueif i + k < n and s[i+k] == c:
continuereturnTruereturnFalse
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
impl Solution {
pubfnhas_special_substring(s: String, k: i32) -> bool {
let n = s.len();
let s = s.as_bytes();
let k = k asusize;
for i in0..=n-k {
let c = s[i];
if (1..k).any(|j| s[i+j] != c) { continue; }
if i >0&& s[i-1] == c { continue; }
if i + k < n && s[i+k] == c { continue; }
returntrue;
}
false }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
classSolution {
hasSpecialSubstring(s: string, k: number):boolean {
constn=s.length;
for (leti=0; i+k<=n; i++) {
constc=s[i];
if ([...Array(k).keys()].some(j=>s[i+j] !==c)) continue;
if (i>0&&s[i-1] ===c) continue;
if (i+k<n&&s[i+k] ===c) continue;
returntrue;
}
returnfalse;
}
}