Input: s ="cabaabac"Output: 0Explanation: An optimal sequence of operations is:- Take prefix ="c" and suffix ="c" and remove them, s ="abaaba".- Take prefix ="a" and suffix ="a" and remove them, s ="baab".- Take prefix ="b" and suffix ="b" and remove them, s ="aa".- Take prefix ="a" and suffix ="a" and remove them, s ="".
Input: s ="aabccabba"Output: 3Explanation: An optimal sequence of operations is:- Take prefix ="aa" and suffix ="a" and remove them, s ="bccabb".- Take prefix ="b" and suffix ="bb" and remove them, s ="cca".
We use two pointers to shrink the string from both ends as long as the characters at both ends are the same. We keep removing matching prefixes and suffixes until the pointers meet or the characters differ.
classSolution {
public:int minimumLength(string s) {
int l =0, r = s.size() -1;
while (l < r && s[l] == s[r]) {
char c = s[l];
while (l <= r && s[l] == c) ++l;
while (r >= l && s[r] == c) --r;
}
return r - l +1;
}
};
classSolution {
publicintminimumLength(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 (r >= l && s.charAt(r) == c) r--;
}
return r - l + 1;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
classSolution {
funminimumLength(s: String): Int {
var l = 0var r = s.length - 1while (l < r && s[l] == s[r]) {
val c = s[l]
while (l <= r && s[l] == c) l++while (r >= l && s[r] == c) r-- }
return r - l + 1 }
}
1
2
3
4
5
6
7
8
9
defminimum_length(s: str) -> int:
l, r =0, len(s) -1while l < r and s[l] == s[r]:
c = s[l]
while l <= r and s[l] == c:
l +=1while r >= l and s[r] == c:
r -=1return r - l +1
1
2
3
4
5
6
7
8
9
10
11
12
impl Solution {
pubfnminimum_length(s: String) -> i32 {
let s = s.as_bytes();
let (mut l, mut r) = (0, s.len() -1);
while l < r && s[l] == s[r] {
let c = s[l];
while l <= r && s[l] == c { l +=1; }
while r >= l && s[r] == c { r -=1; }
}
(r asi32) - (l asi32) +1 }
}
1
2
3
4
5
6
7
8
9
10
11
classSolution {
minimumLength(s: string):number {
letl=0, r=s.length-1;
while (l<r&&s[l] ===s[r]) {
constc=s[l];
while (l<=r&&s[l] ===c) l++;
while (r>=l&&s[r] ===c) r--;
}
returnr-l+1;
}
}