Minimum Length of String After Deleting Similar Ends

medium two pointers string

Problem

Repeatedly remove a non-empty prefix and an equal-length non-empty suffix that share the same single character, requiring l

Inputs = "cabaabac"
Output0
Strip "c…c" → "abaaba"; "a…a" → "baab"; "b…b" → "aa"; "a…a" → "".

def minimum_length(s):
    l, r = 0, len(s) - 1
    while l < r and s[l] == s[r]:
        c = s[l]
        while l <= r and s[l] == c: l += 1
        while l <= r and s[r] == c: r -= 1
    return max(0, r - l + 1)
function minimumLength(s) {
  let l = 0, r = s.length - 1;
  while (l < r && s[l] === s[r]) {
    const c = s[l];
    while (l <= r && s[l] === c) l++;
    while (l <= r && s[r] === c) r--;
  }
  return Math.max(0, r - l + 1);
}
class Solution {
    public int minimumLength(String s) {
        int l = 0, r = s.length() - 1;
        while (l < r && s.charAt(l) == s.charAt(r)) {
            char c = s.charAt(l);
            while (l <= r && s.charAt(l) == c) l++;
            while (l <= r && s.charAt(r) == c) r--;
        }
        return Math.max(0, r - l + 1);
    }
}
int minimumLength(string s) {
    int l = 0, r = (int)s.size() - 1;
    while (l < r && s[l] == s[r]) {
        char c = s[l];
        while (l <= r && s[l] == c) l++;
        while (l <= r && s[r] == c) r--;
    }
    return max(0, r - l + 1);
}
Time: O(n) Space: O(1)