题目如下:
You are given a string
s
consisting only of characters'a'
and'b'
.You can delete any number of characters in
s
to makes
balanced.s
is balanced if there is no pair of indices(i,j)
such thati < j
ands[i] = 'b'
ands[j]= 'a'
.Return the minimum number of deletions needed to make
s
balanced.Example 1:
Input: s = "aababbab" Output: 2 Explanation: You can either: Delete the characters at 0-indexed positions 2 and 6 ("aababbab" -> "aaabbb"), or Delete the characters at 0-indexed positions 3 and 6 ("aababbab" -> "aabbbb").Example 2:
Input: s = "bbaaaaabb" Output: 2 Explanation: The only solution is to delete the first two characters.Constraints:
1 <= s.length <= 105
s[i]
is'a'
or'b'
.
解题思路:要使得s是一个Balanced的字符串,有两种情况,一个是把'a'全部删除,另一个是前半部分是'a'后半部分是'b'的字符串。第二种情况的关键在于找出Balanced后的字符串的最后一个'a',假设其下标为index,那么删除操作的次数就是index前面'b'的个数加上index后面'a'的个数。
代码如下:
class Solution(object): def minimumDeletions(self, s): """ :type s: str :rtype: int """ count_a = s.count('a') count_b = 0 res = len(s) - count_a for i in range(len(s)): if s[i] == 'a': count_a -= 1 continue res = min(res,count_b + count_a) count_b += 1 return res