You are given a string `s` made only of the characters `'a'` and `'b'`. The string is balanced when there is no pair of indices `i < j` with `s[i] = 'b'` and `s[j] = 'a'`, that is, every `'a'` comes before every `'b'`. You may delete any number of characters. Return the minimum number of deletions that makes `s` balanced.
You are given a string s made only of the characters 'a' and 'b'. The string is balanced when there is no pair of indices i < j with s[i] = 'b' and s[j] = 'a', that is, every 'a' comes before every 'b'. You may delete any number of characters. Return the minimum number of deletions that makes s balanced.
Example 1:
Input: {"s":"aababbab"}
Output: 2
Constraints:
1≤s.length≤105
s[i] is 'a' or 'b'.
Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result
Run code to see results.
Input
arr ={"s":"aababbab"}
s: a clashing 'b' and 'a' share a colour
a
0
a
1
b
2
a
3
b
4
b
5
a
6
b
7
Every clash is a 'b' somewhere before an 'a'. Scan left to right, keep the unmatched 'b's on a stack, and cancel one against each 'a' that arrives: each cancelled pair costs exactly one deletion.