Find the Longest Semi-Repetitive Substring Problem
Description
LeetCode Problem 2730.
You are given a digit string s that consists of digits from 0 to 9.
A string is called semi-repetitive if there is at most one adjacent pair of the same digit. For example, "0010", "002020", "0123", "2002", and "54944" are semi-repetitive while the following are not: "00101022" (adjacent same digit pairs are 00 and 22), and "1101234883" (adjacent same digit pairs are 11 and 88).
Return the length of the longest semi-repetitive substring of s.
Example 1:
Input: s = "52233"
Output: 4
Explanation:
The longest semi-repetitive substring is "5223". Picking the whole string "52233" has two adjacent same digit pairs 22 and 33, but at most one is allowed.
Example 2:
Input: s = "5494"
Output: 4
Explanation:
s is a semi-repetitive string.
Example 3:
Input: s = "1111111"
Output: 2
Explanation:
The longest semi-repetitive substring is "11". Picking the substring "111" has two adjacent same digit pairs, but at most one is allowed.
Constraints:
1 <= s.length <= 50'0' <= s[i] <= '9'
Solution
Approach: Sliding Window
Keep a window s[j..i] that contains at most one pair of equal adjacent characters. Let cnt be the number of such pairs inside the window.
Move i to the right. When s[i] == s[i - 1], cnt grows by one. While cnt > 1, advance the left end j, and each time s[j] == s[j + 1] the pair that leaves the window reduces cnt by one. After the window is valid again, update the answer with its length i - j + 1. The answer starts at 1 (a single digit is always semi-repetitive).
Complexity: O(n) time and O(1) extra space.
class Solution:
def longestSemiRepetitiveSubstring(self, s: str) -> int:
ans, n = 1, len(s)
cnt = j = 0
for i in range(1, n):
cnt += s[i] == s[i - 1]
while cnt > 1:
cnt -= s[j] == s[j + 1]
j += 1
ans = max(ans, i - j + 1)
return ans