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:
- Pick a non-empty prefix from the string
s
where all the characters in the prefix are equal. - Pick a non-empty suffix from the string
s
where all the characters in this suffix are equal. - The prefix and the suffix should not intersect at any index.
- The characters from the prefix and suffix must be the same.
- Delete both the prefix and the suffix.
Return the minimum length of s
after performing the above operation any number of times (possibly zero times).
Input: s = "ca" Output: 2 Explanation: You can't remove any characters, so the string stays as is.
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 = "".
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".
1 <= s.length <= 105
s
only consists of characters'a'
,'b'
, and'c'
.
# @param {String} s
# @return {Integer}
def minimum_length(s)
i = 0
j = s.size - 1
while i < j && s[i] == s[j]
c = s[i]
i += 1 while i < j && s[i] == c
return 0 if i == j
j -= 1 while i < j && s[j] == c
end
j - i + 1
end
impl Solution {
pub fn minimum_length(s: String) -> i32 {
let s = s.as_bytes();
let mut i = 0;
let mut j = s.len() - 1;
while i < j && s[i] == s[j] {
let c = s[i];
while i < j && s[i] == c {
i += 1;
}
if i == j {
return 0;
}
while i < j && s[j] == c {
j -= 1;
}
}
(j - i + 1) as i32
}
}