Violence
1 2 3 4 5 6 7 8 9 10 11 12
| class Solution { public int minLength(String s) { for (int i = 0; i < s.length() - 1; i++) { char c1 = s.charAt(i), c2 = s.charAt(i + 1); if ((c1 == 'A' && c2 == 'B') || (c1 == 'C' && c2 == 'D')) { return minLength(s.substring(0, i) + s.substring(i + 2)); } }
return s.length(); } }
|
Stack
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| class Solution { public int minLength(String s) { Stack<Character> stack = new Stack<>();
for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (!stack.isEmpty() && ((stack.peek() == 'A' && c == 'B') || (stack.peek() == 'C' && c == 'D'))) { stack.pop(); } else { stack.push(c); } } return stack.size(); } }
|
References
2696. Minimum String Length After Removing Substrings