Find the Longest Semi-Repetitive Substring - Problem
You are given a digit string s consisting of digits from 0 to 9. Your task is to find the longest semi-repetitive substring within this string.
A string is considered semi-repetitive if it contains at most one adjacent pair of the same digit. Think of it as allowing only one "double" digit occurrence in the entire substring.
Examples of semi-repetitive strings:
"0010"- has one adjacent pair (00)"002020"- has one adjacent pair (00)"0123"- has no adjacent pairs"2002"- has one adjacent pair (00)"54944"- has one adjacent pair (44)
Examples of NON semi-repetitive strings:
"00101022"- has two adjacent pairs: (00) and (22)"1101234883"- has two adjacent pairs: (11) and (88)
Return the length of the longest semi-repetitive substring of s.
Input & Output
example_1.py โ Basic Case
$
Input:
s = "52233"
โบ
Output:
4
๐ก Note:
The longest semi-repetitive substring is "5223" with length 4. It contains exactly one adjacent duplicate pair (22).
example_2.py โ No Duplicates
$
Input:
s = "5494"
โบ
Output:
4
๐ก Note:
The entire string "5494" is semi-repetitive as it has no adjacent duplicate pairs. The length is 4.
example_3.py โ Single Character
$
Input:
s = "1"
โบ
Output:
1
๐ก Note:
A single character string is always semi-repetitive. The length is 1.
Constraints
- 1 โค s.length โค 1000
-
s consists only of digits from
'0'to'9' - The string is guaranteed to be non-empty
Visualization
Tap to expand
Understanding the Visualization
1
Start Small
Begin with a minimal window of size 1
2
Expand Greedily
Keep expanding the window as long as you have โค 1 duplicate pair
3
Contract When Needed
When you exceed 1 duplicate pair, shrink from the left
4
Track Maximum
Remember the largest valid window size you've seen
Key Takeaway
๐ฏ Key Insight: Use sliding window to maintain a substring with at most one adjacent duplicate pair, expanding greedily and contracting only when necessary.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code