Welcome to Subscribe On Youtube
3456. Find Special Substring of Length K
Description
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:
- The substring consists of only one distinct character (e.g.,
"aaa"
or"bbb"
). - If there is a character immediately before the substring, it must be different from the character in the substring.
- 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
.
Example 1:
Input: s = "aaabaaa", k = 3
Output: true
Explanation:
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"
.
Example 2:
Input: s = "abc", k = 2
Output: false
Explanation:
There is no substring of length 2 that consists of one distinct character and satisfies the conditions.
Constraints:
1 <= k <= s.length <= 100
s
consists of lowercase English letters only.
Solutions
Solution 1: Two Pointers
The problem essentially asks us to find each segment of consecutive identical characters and then determine if there exists a substring of length
We can use two pointers
The time complexity is
-
class Solution { public boolean hasSpecialSubstring(String s, int k) { int n = s.length(); for (int l = 0, cnt = 0; l < n;) { int r = l + 1; while (r < n && s.charAt(r) == s.charAt(l)) { ++r; } if (r - l == k) { return true; } l = r; } return false; } }
-
class Solution { public: bool hasSpecialSubstring(string s, int k) { int n = s.length(); for (int l = 0, cnt = 0; l < n;) { int r = l + 1; while (r < n && s[r] == s[l]) { ++r; } if (r - l == k) { return true; } l = r; } return false; } };
-
class Solution: def hasSpecialSubstring(self, s: str, k: int) -> bool: l, n = 0, len(s) while l < n: r = l while r < n and s[r] == s[l]: r += 1 if r - l == k: return True l = r return False
-
func hasSpecialSubstring(s string, k int) bool { n := len(s) for l := 0; l < n; { r := l + 1 for r < n && s[r] == s[l] { r++ } if r-l == k { return true } l = r } return false }
-
function hasSpecialSubstring(s: string, k: number): boolean { const n = s.length; for (let l = 0; l < n; ) { let r = l + 1; while (r < n && s[r] === s[l]) { r++; } if (r - l === k) { return true; } l = r; } return false; }