Problem Description
Given a digit string s, find the length of the longest contiguous substring that is semi-repetitive, where a substring is called semi-repetitive if it contains at most one pair of adjacent identical digits.
Key Insights
- Use a sliding window (two-pointer) approach to efficiently inspect substrings.
- As you extend the window, count the number of adjacent duplicate pairs.
- When the count exceeds one, shrink the window from the left until the count is at most one again.
- Care should be taken when adjusting the count when the left pointer moves past a duplicate pair boundary.
Space and Time Complexity
Time Complexity: O(n), where n is the length of s, because each character is processed at most twice. Space Complexity: O(1), as only a few variables are used.
Solution
We use a two-pointer or sliding window approach:
- Initialize two pointers (“left” and “right”) at the start of the string.
- Keep a counter for the number of adjacent duplicate pairs found within the current window.
- As you move the “right” pointer:
- If the current character is the same as the previous, increment the duplicate counter.
- If the counter exceeds one (meaning more than one adjacent duplicate pair exists), move the “left” pointer forward. While doing so, if a duplicate pair that is leaving the window is encountered (i.e., if s[left] equals s[left + 1]), decrement the counter.
- Track and update the maximum window length where the duplicate counter remains at most one.
- Return the maximum length found.