Given a string s
consisting only of characters 'a'
, 'b'
, and 'c'
. You are asked to apply the following algorithm on the string any number of times:
s
where all the characters in the prefix are equal.s
where all the characters in this suffix are equal.Return the minimum length of s
after performing the above operation any number of times (possibly zero times).
Example 1:
Input: s = "ca" Output: 2 Explanation: You can't remove any characters, so the string stays as is.
Example 2:
Input: s = "cabaabac" Output: 0 Explanation: 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 = "".
Example 3:
Input: s = "aabccabba" Output: 3 Explanation: 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".
Constraints:
1 <= s.length <= 105
s
only consists of characters 'a'
, 'b'
, and 'c'
.struct Solution;
use std::collections::VecDeque;
impl Solution {
fn minimum_length(s: String) -> i32 {
let mut queue: VecDeque<char> = s.chars().collect();
while !queue.is_empty() {
let size = queue.len();
if size == 1 {
break;
}
let c = *queue.front().unwrap();
if queue.front() == queue.back() {
while let Some(&x) = queue.front() {
if x == c {
queue.pop_front();
} else {
break;
}
}
while let Some(&x) = queue.back() {
if x == c {
queue.pop_back();
} else {
break;
}
}
} else {
break;
}
}
queue.len() as i32
}
}
#[test]
fn test() {
let s = "ca".to_string();
let res = 2;
assert_eq!(Solution::minimum_length(s), res);
let s = "cabaabac".to_string();
let res = 0;
assert_eq!(Solution::minimum_length(s), res);
let s = "aabccabba".to_string();
let res = 3;
assert_eq!(Solution::minimum_length(s), res);
}