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: DP
dp[i][0] := min # of dels to make s[0:i] all ‘a’s;
dp[i][1] := min # of dels to make s[0:i] ends with 0 or mode ‘b’s
if s[i-1] == ‘a’:
dp[i + 1][0] = dp[i][0], dp[i + 1][1] = min(dp[i + 1][0], dp[i][1] + 1)
else:
dp[i + 1][0] = dp[i][0] + 1, dp[i + 1][1] = dp[i][1]
Time complexity: O(n)
Space complexity: O(n) -> O(1)
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
// Author: Huahua class Solution { public: int minimumDeletions(string s) { // const int n = s.length(); // dp[i][0] := min # of dels to make s[0:i] all 'a's; // dp[i][1] := min # of dels to make s[0:i] ends with 0+ 'b's // vector<vector<int>> dp(n + 1, vector<int>(2)); // for (int i = 0; i < n; ++i) { // if (s[i] == 'a') { // dp[i + 1][0] = dp[i][0]; // dp[i + 1][1] = min(dp[i + 1][0], dp[i][1] + 1); // } else { // dp[i + 1][0] = dp[i][0] + 1; // dp[i + 1][1] = dp[i][1]; // } // } // return min(dp[n][0], dp[n][1]); int a = 0, b = 0; for (char c : s) { if (c == 'a') b = min(a, b + 1); else ++a; } return min(a, b); } }; |
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment