#1750
Medium Algorithms Minimum length of string after deleting similar ends
Two Pointers String
56.1% acceptance
Feb 25, 2026
1317
111
You are given a string s consisting only of characters 'a' and 'b' on which you can apply the following delete operation once per turn:
Choose any character in s and delete it if both adjacent characters are equal.
Return the minimum possible length of s after performing the above operation any number of times.
Note: After you delete a character in s, other characters around it will move to fill the gap.
Actually: You are given a string s consisting only of characters 'a' and 'b'. Delete similar ends: while both ends are the same character, remove all occurrences of that character from both ends.
Solution
Rust
Time O(n²)
Space O(1)
impl Solution {
pub fn minimum_length(s: String) -> i32 {
let s = s.as_bytes();
let mut l = 0usize;
let mut r = 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; }
if l > r { break; }
if s[r] == c { break; }
}
if l > r { 0 } else { (r - l + 1) as i32 }
}
}