Find the Longest Semi-Repetitive Substring

medium string sliding window two pointers

Problem

You are given a string s made up of digits. A string is called semi-repetitive if it contains at most one place where two side-by-side characters are equal (in other words, at most one adjacent equal pair). Return the length of the longest contiguous substring of s that is semi-repetitive.

Inputs = "52233"
Output4
The whole string has two adjacent equal pairs: "22" and "33". The substring "5223" (indices 0..3) has only the pair "22", so it is semi-repetitive and has length 4. No semi-repetitive substring is longer.

def longest_semi_repetitive_substring(s):
    left = 0
    pairs = 0
    best = 1
    for right in range(1, len(s)):
        if s[right] == s[right - 1]:
            pairs += 1
        while pairs > 1:
            if s[left] == s[left + 1]:
                pairs -= 1
            left += 1
        best = max(best, right - left + 1)
    return best
function longestSemiRepetitiveSubstring(s) {
  let left = 0;
  let pairs = 0;
  let best = 1;
  for (let right = 1; right < s.length; right++) {
    if (s[right] === s[right - 1]) {
      pairs += 1;
    }
    while (pairs > 1) {
      if (s[left] === s[left + 1]) {
        pairs -= 1;
      }
      left += 1;
    }
    best = Math.max(best, right - left + 1);
  }
  return best;
}
class Solution {
    public int longestSemiRepetitiveSubstring(String s) {
        int left = 0;
        int pairs = 0;
        int best = 1;
        for (int right = 1; right < s.length(); right++) {
            if (s.charAt(right) == s.charAt(right - 1)) {
                pairs += 1;
            }
            while (pairs > 1) {
                if (s.charAt(left) == s.charAt(left + 1)) {
                    pairs -= 1;
                }
                left += 1;
            }
            best = Math.max(best, right - left + 1);
        }
        return best;
    }
}
int longestSemiRepetitiveSubstring(string s) {
    int left = 0;
    int pairs = 0;
    int best = 1;
    for (int right = 1; right < (int)s.size(); right++) {
        if (s[right] == s[right - 1]) {
            pairs += 1;
        }
        while (pairs > 1) {
            if (s[left] == s[left + 1]) {
                pairs -= 1;
            }
            left += 1;
        }
        best = max(best, right - left + 1);
    }
    return best;
}
Time: O(n) Space: O(1)