Leetcode 1717. Maximum Score From Removing Substrings
12 Jul 2024leetcode
medium
stack
2024/07/12 的每日一題!
題目描述
You are given a string s and two integers x and y. You can perform two types of operations any number of times.
- Remove substring
"ab"
and gainx
points.- For example, when removing
"ab"
from"cabxbae"
it becomes"cxbae"
.
- For example, when removing
- Remove substring
"ba"
and gainy
points.- For example, when removing
"ba"
from"cabxbae"
it becomes"cabxe"
. Return the maximum points you can gain after applying the above operations ons
.
- For example, when removing
範例
Example 1:
Input: s = "cdbcbbaaabab", x = 4, y = 5
Output: 19
Explanation:
- Remove the "ba" underlined in "cdbcbbaaabab". Now, s = "cdbcbbaaab" and 5 points are added to the score.
- Remove the "ab" underlined in "cdbcbbaaab". Now, s = "cdbcbbaa" and 4 points are added to the score.
- Remove the "ba" underlined in "cdbcbbaa". Now, s = "cdbcba" and 5 points are added to the score.
- Remove the "ba" underlined in "cdbcba". Now, s = "cdbc" and 5 points are added to the score.
Total score = 5 + 4 + 5 + 5 = 19.
Example 2:
Input: s = "aabbaaxybbaabb", x = 5, y = 4
Output: 20
Constraints:
- 1 <= s.length <= 10^5
- 1 <= x, y <= 10^4
s
consists of lowercase English letters.
解法
方法:寫一個叫做 remove
的方法,該方法利用 stack 消除所有 removestr,並將每個 removestr 作為 val 值加總在一起並回傳。
針對題目字串,如果x較大,我們就先處理 ab,如 y 較大,處理 ba。
func maximumGain(s string, x int, y int) int {
remove := func(str string, removestr string, val int) int {
count := 0
stack := make([]byte, 0)
for i:=0; i<len(str); i++ {
stack = append(stack, str[i])
l := len(stack)
if l >= 2 && stack[l-1]==removestr[1] && stack[l-2]==removestr[0] {
count += val
stack = stack[:l-2]
}
}
s = string(stack)
return count
}
if x > y {
return remove(s, "ab", x) + remove(s, "ba", y)
} else {
return remove(s, "ba", y) + remove(s, "ab", x)
}
return 0
}
Time complexity : O(n) Space complexity : O(n)