leetcode - 1653. Minimum Deletions to Make String Balanced
迪丽瓦拉
2024-05-29 20:00:46
0

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'​​.

Solution

Find the balance point, all the chars at the left of this point would be a, and the right would be b, iterate the s to find the best balance point

At the balance point, all you need to do is: delete all the bs at the left and all the as at the right. The number of b at the left would be all the bs that you have already visited, and all the as at the right would be the number of a in s minus the a you have visited.

Time complexity: o(n)o(n)o(n)
Space complexity: o(1)o(1)o(1)

Code

class Solution:def minimumDeletions(self, s: str) -> int:cnt = {}for char in s:cnt[char] = cnt.get(char, 0) + 1a_cnt, b_cnt = 0, 0res = b_cnt + cnt.get('a', 0) - a_cntfor balance_point in range(1, len(s) + 1):if s[balance_point - 1] == 'a':a_cnt += 1else:b_cnt += 1delete_cnt = b_cnt + cnt.get('a', 0) - a_cntres = min(res, delete_cnt)return res

相关内容