Leetcode 2730: Find the Longest Semi-Repetitive Substring

grid47
grid47
Exploring patterns and algorithms
Feb 8, 2024 6 min read

You are given a string s consisting of digits from ‘0’ to ‘9’. A string is called semi-repetitive if there is at most one pair of adjacent identical digits. Your task is to return the length of the longest semi-repetitive substring of s.
Problem
Approach
Steps
Complexity
Input: A string s consisting of digits from 0 to 9.
Example: s = '33342'
Constraints:
• 1 <= s.length <= 50
• Each character of s is a digit from '0' to '9'.
Output: Return the length of the longest semi-repetitive substring of s.
Example: 4
Constraints:
• The result will be an integer value.
Goal: Find the longest semi-repetitive substring by ensuring there is at most one adjacent pair of identical digits.
Steps:
• Traverse the string and track adjacent identical digits.
• If more than one adjacent identical pair is found, adjust the substring to remove excess pairs.
• Keep track of the maximum length of the semi-repetitive substrings.
Goal: The constraints define the length of the string and the range of digits it can contain.
Steps:
• 1 <= s.length <= 50
• The string consists of digits from '0' to '9'.
Assumptions:
• The input string is always a valid sequence of digits.
Input: Example 1
Explanation: For s = '33342', the longest semi-repetitive substring is '3334' since it contains only one adjacent same digit pair (33).

Input: Example 2
Explanation: For s = '1223', the longest semi-repetitive substring is '1223' as there is at most one adjacent same digit pair.

Input: Example 3
Explanation: For s = '11122233', the longest semi-repetitive substring is '111', which only contains one adjacent same digit pair.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus