Problem Description
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. Return the length of the longest semi-repetitive substring of s.
Key Insights
- A semi-repetitive substring contains at most one pair of adjacent identical digits.
- We can use a sliding window approach to maintain a substring while checking for the number of adjacent pairs.
- We need to efficiently track the pairs of adjacent digits as we expand and contract our window.
Space and Time Complexity
Time Complexity: O(n), where n is the length of the string s. We traverse the string at most twice (once for expanding the window and once for contracting it). Space Complexity: O(1), as we only use a fixed amount of extra space for counters and pointers regardless of the input size.
Solution
We will use a sliding window approach to find the longest semi-repetitive substring. The algorithm will maintain two pointers (left and right) to represent the current window. As we expand the right pointer to include more characters in the window, we will check for the number of adjacent pairs. If the count exceeds one, we will move the left pointer to shrink the window until we have at most one pair. Throughout the process, we will keep track of the maximum length of valid windows found.