Question
Formatted question description: https://leetcode.ca/all/1653.html
1653. Minimum Deletions to Make String Balanced
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'.
Algorithm
We only need to enumerate the demarcation points.
For example, we enumerate s[0:k] are all a, and s[k+1:len-1] are all b, then only need to know how many b are in s[0:k], and how many a in s[k+1:len-1].
Code
Java
public class Minimum_Deletions_to_Make_String_Balanced {
public class Solution {
public int minimumDeletions(String s) {
if (s == null || s.length() == 0) {
return 0;
}
int aCount = 0;
int bCount = 0;
for (int i = 0; i < s.length(); i++) {
aCount += s.charAt(i) == 'a' ? 1 : 0;
}
// all a to b
int res = aCount;
for (int i = 0; i < s.length(); i++) {
bCount += s.charAt(i) == 'b' ? 1 : 0;
aCount -= s.charAt(i) == 'a' ? 1 : 0;
res = Math.min(res, bCount + aCount);
}
return res;
}
}
}