Skip to main content
Back to problems
#2730
Medium Algorithms

Find the longest semi repetitive substring

String Sliding Window
38.5% acceptance
Feb 25, 2026
318
89
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.

Solution

Rust
Time O(n²)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn longest_semi_repetitive_substring(s: String) -> i32 {
    let s = s.as_bytes();
    let n = s.len();
    let mut left = 0usize;
    let mut pairs = 0usize;
    let mut ans = 1usize;
    for right in 1..n {
      if s[right] == s[right - 1] { pairs += 1; }
      while pairs > 1 {
        if s[left + 1] == s[left] { pairs -= 1; }
        left += 1;
      }
      ans = ans.max(right - left + 1);
    }
    ans as i32
  }
}