Description
You are given a string s consisting only of characters ‘a’ and 'b’.
You can delete any number of characters in s to make s balanced. s is balanced if there is no pair of indices (i,j) such that i < j and s[i] = ‘b’ and s[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,删除其中的字符,使得字符串平衡,即前半部分为全a,后半部分为全b。
- 这道题我参考了一下别人的解法,count_a记录的是需要删除的a的数量,count_b记录的是当前遍历的需要删除的b的数量。
- 如果当前遍历到的是a,则count_a减去1,更新res。
res=min(res,count_a+count_b)
- 如果当前遍历到的是b,则count_b加上1,更新res。
res=min(res,count_a+count_b-1)
代码
class Solution:
def minimumDeletions(self, s: str) -> int:
count_a=s.count('a')
count_b=0
res=float('inf')
for ch in s:
if(ch=='a'): # 如果选择当前的索引为a的结束
count_a-=1
res=min(res,count_a+count_b)
elif(ch=='b'): #如果选择当前的索引为b的开始
count_b+=1
res=min(res,count_a+count_b-1)
return res
参考文献
Python one-pass solution with comments