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 <= 100sconsists of lowercase English letters only.
Solutions
Solution 1: Two Pointers
Thinking
A special substring is a run of one letter whose length is exactly \(k\), not a piece of a longer run. \(|s|\le 100\), so a run-length scan is enough.
A window of length \(k\) would accept a slice of a longer identical run when both ends match.
Two pointers isolate each constant run and succeed only when the run length equals \(k\).
The problem essentially asks us to find each segment of consecutive identical characters and then determine if there exists a substring of length \(k\). If such a substring exists, return \(\textit{true}\); otherwise, return \(\textit{false}\).
We can use two pointers \(l\) and \(r\) to traverse the string \(s\). When \(s[l] = s[r]\), move \(r\) to the right until \(s[r] \neq s[l]\). At this point, check if \(r - l\) equals \(k\). If it does, return \(\textit{true}\); otherwise, move \(l\) to \(r\) and continue traversing.
The time complexity is \(O(n)\), where \(n\) is the length of the string \(s\). The space complexity is \(O(1)\).
1 2 3 4 5 6 7 8 9 10 11 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | |