LeetCode 1750. Minimum Length of String After Deleting Similar E
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).
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".
写了3个函数,
1:判断左右两端是否一样,用来做循环的条件;
2:判断左边一样的到哪里;
3:判断右边一样的到哪里;
依次循环,处理返回即可;
但是长度为1的需要特殊处理一下即可;
只是没想到还能速度这么快。。。。
下面是代码:
Constraints:
1 <= s.length <= 105
s
only consists of characters'a'
,'b'
, and'c'
.
Runtime: 5 ms, faster than 88.12% of Java online submissions for Minimum Length of String After Deleting Similar Ends.
Memory Usage: 43.1 MB, less than 60.54% of Java online submissions for Minimum Length of String After Deleting Similar Ends.