0
点赞
收藏
分享

微信扫一扫

photoshop学习笔记——移动工具

唯米天空 2024-07-30 阅读 18

Minimum Deletions to Make String Balanced

Problem Statement

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. The string 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.

Examples

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 \leq s.length \leq 10^5)
  • s[i] is ‘a’ or ‘b’.

Solution

class Solution:
    def minimumDeletions(self, s: str) -> int:
        n = len(s)
        prefix_b = 0  # Count of 'b's up to current position
        suffix_a = s.count('a')  # Initial count of 'a's from the start to the end
        result = suffix_a  # Initialize result with the total count of 'a's
        
        for i in range(n):
            if s[i] == 'a':
                suffix_a -= 1  # Decrease suffix_a as we encounter 'a'
            else:
                prefix_b += 1  # Increase prefix_b as we encounter 'b'
            
            # Update the minimum deletions needed at each position
            result = min(result, prefix_b + suffix_a)
        
        return result

Explanation of the Solution

  1. Initialization:

    • prefix_b starts at 0 since no 'b’s have been counted yet.
    • suffix_a is initialized to the total count of 'a’s in the string.
    • result is initialized to the total count of 'a’s because, in the worst case, we might need to delete all 'a’s.
  2. Single Iteration:

    • Iterate through the string once.
    • If the current character is ‘a’, decrement suffix_a since one ‘a’ is being accounted for as we move from left to right.
    • If the current character is ‘b’, increment prefix_b.
    • At each step, update the result with the minimum of the current result and the sum of prefix_b and suffix_a.
  3. Return Result:

    • The result will hold the minimum deletions needed to make the string balanced.

This optimized solution maintains a linear time complexity (O(n)) and requires constant space (O(1)) in addition to the input string.

举报

相关推荐

0 条评论