#1750

Minimum Length of String After Deleting Similar Ends

specialist · 780 · lc medium +31 · verified · 56.1% accepted · 1,317 likes · top 50%

Description

Given a string s of only 'a', 'b', and 'c', repeatedly pick a non-empty uniform prefix and a non-empty uniform suffix sharing the same character that do not overlap, and delete both. Return the minimum length of s after any number of such operations.

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".

Code

1
2
3