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 <= 105s[i] is 'a' or 'b'.class Solution {
public int minimumDeletions(String s) {
char[] S = s.toCharArray();
int n = S.length, prefixB = 0;
int[] dp = new int[n + 1];
for (int i = 0; i < n; i++) {
if (S[i] == 'a')
dp[i + 1] = Math.min(dp[i] + 1, prefixB);
// delete 'a', delete all prefix 'b'(s)
else {
dp[i + 1] = dp[i];
prefixB++;
}
}
return dp[n];
}
}class Solution {
public int minimumDeletions(String s) {
int n = s.length();
char[] S = s.toCharArray();
int suffixA = 0, prefixB = 0, deletionCt = Integer.MAX_VALUE;
for(int i=0; i<n; i++)
if(S[i]=='a')
suffixA++;
for(int i=0; i<n; i++){
if(S[i]=='a')
--suffixA;
deletionCt = Math.min(deletionCt, prefixB+suffixA);
if(S[i]=='b')
prefixB++;
}
return deletionCt;
}
}class Solution {
public int minimumDeletions(String s) {
char[] S = s.toCharArray();
int n = S.length, prefixB = 0;
int[] dp = new int[n + 1];
for (int i = 0; i < n; i++) {
if (S[i] == 'a')
dp[i + 1] = Math.min(dp[i] + 1, prefixB);
// delete 'a', delete all prefix 'b'(s)
else {
dp[i + 1] = dp[i];
prefixB++;
}
}
return dp[n];
}
}