Repeatedly remove matching groups from both ends of a string until the ends differ.
You are given a string s. You may repeatedly perform the following operation:
s consisting of the same character.s consisting of the same character.Keep applying the operation as long as possible. Return the minimum possible length of the string after all valid deletions.
Compute the length of the shortest string that can remain after deleting similar ends from both sides.
s.s contains lowercase English letters.s consists of lowercase English letters only.Example 1
Input
s = "ca"
Output
2
Explanation
The first and last characters are different, so no deletion is possible.
Example 2
Input
s = "cabaabac"
Output
0
Explanation
You can delete matching ends repeatedly until the string becomes empty.
Example 3
Input
s = "aabccabba"
Output
3
Explanation
After removing matching ends as much as possible, the remaining middle part has length 3.
Premium problem context
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.