MediumNo. 2730
Find the Longest Semi-Repetitive Substring — LeetCode 2730 Python Solution
- Pattern
- Sliding Window
- Topics
- String, Sliding Window
- Reading time
- 2 min
- Source
- leetcode.com
The problem
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.
Python solution
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 ansComplexity
- Time
- O(n)where n is the length of the string
- Space · auxiliary
- O(1)
Pattern: Sliding Window
Collapse a nested loop over every subarray into a single pass with two indices. LeetCode 2730. Find the Longest Semi-Repetitive Substring is filed here because LeetCode tags it Sliding Window, which is the vocabulary this hub collects.
The sliding window guide has the Python template for the pattern and the 116 LeetCode problems that use it.
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 1044 | Longest Duplicate Substring | Hard |
| 1208 | Get Equal Substrings Within Budget | Medium |
| 1234 | Replace the Substring for Balanced String | Medium |
| 1456 | Maximum Number of Vowels in a Substring of Given Length | Medium |
| 1839 | Longest Substring Of All Vowels in Order | Medium |
| 1871 | Jump Game VII | Medium |
Frequently asked questions
- How hard is LeetCode 2730. Find the Longest Semi-Repetitive Substring?
LeetCode 2730. Find the Longest Semi-Repetitive Substring is rated Medium on LeetCode.
- What is the time complexity of LeetCode 2730. Find the Longest Semi-Repetitive Substring?
The Python solution on this page runs in O(n), where n is the length of the string.
- What is the space complexity of LeetCode 2730. Find the Longest Semi-Repetitive Substring?
The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 2730. Find the Longest Semi-Repetitive Substring cover?
LeetCode 2730. Find the Longest Semi-Repetitive Substring is tagged String and Sliding Window on LeetCode.