Problem
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"
.
- For example, when removing
Return the maximum points you can gain after applying the above operations on s
.
Examples
Example 1:
|
|
Example 2:
|
|
Solution
Method 1 - Using StringBuilder as Stack
Here’s one way to achieve this:
- Decide the order of removal based on the point values
x
andy
. Always start with the operation that gives the higher points. - Use a stack to process the string and remove substrings when detected.
- After processing once for one substring, process the resulting string for the other substring.
- Uses a stack-like mechanism with
StringBuilder
to process and remove substrings. - Iterates through the input string, maintaining a running result in the
StringBuilder
. - Checks the end of
StringBuilder
for the substring to be removed, and if found, removes it and adds points.
- Uses a stack-like mechanism with
Code
|
|
Complexity
- ⏰ Time complexity:
O(n)
- 🧺 Space complexity:
O(n)