|
1 | 1 | class Solution {
|
2 | 2 | public int maximumGain(String s, int x, int y) {
|
3 |
| - int score = 0; |
4 |
| - String firstPass = removeSubstring(s, x > y ? "ab" : "ba"); |
5 |
| - int removeCount = (s.length() - firstPass.length()) / 2; |
6 |
| - score += removeCount * Math.max(x, y); |
7 |
| - String secondPass = removeSubstring(firstPass, x > y ? "ba" : "ab"); |
8 |
| - removeCount = (firstPass.length() - secondPass.length()) / 2; |
9 |
| - score += removeCount * Math.min(x, y); |
10 |
| - return score; |
11 |
| - } |
12 |
| - |
13 |
| - private String removeSubstring(String s, String target) { |
14 |
| - Stack<Character> stack = new Stack<>(); |
| 3 | + // Swap if x < y so we can follow a single iteration |
| 4 | + if (x < y) { |
| 5 | + int temp = x; |
| 6 | + x = y; |
| 7 | + y = temp; |
| 8 | + s = new StringBuilder(s).reverse().toString(); |
| 9 | + } |
| 10 | + int countA = 0; |
| 11 | + int countB = 0; |
| 12 | + int total = 0; |
15 | 13 | for (int i = 0; i < s.length(); i++) {
|
16 | 14 | char c = s.charAt(i);
|
17 |
| - if (c == target.charAt(1) && !stack.isEmpty() && stack.peek() == target.charAt(0)) { |
18 |
| - stack.pop(); |
| 15 | + if (c == 'a') { |
| 16 | + countA++; |
| 17 | + } else if (c == 'b') { |
| 18 | + // Make a pair to consume the excess 'a' count |
| 19 | + if (countA > 0) { |
| 20 | + countA--; |
| 21 | + total += x; |
| 22 | + } else { |
| 23 | + countB++; |
| 24 | + } |
19 | 25 | } else {
|
20 |
| - stack.push(c); |
| 26 | + // Consume any possible number of pairs & reset the counter |
| 27 | + total += Math.min(countA, countB) * y; |
| 28 | + countA = 0; |
| 29 | + countB = 0; |
21 | 30 | }
|
22 | 31 | }
|
23 |
| - StringBuilder sb = new StringBuilder(); |
24 |
| - while (!stack.isEmpty()) { |
25 |
| - sb.append(stack.pop()); |
26 |
| - } |
27 |
| - return sb.reverse().toString(); |
| 32 | + total += Math.min(countA, countB) * y; |
| 33 | + return total; |
28 | 34 | }
|
29 | 35 | }
|
0 commit comments