通过万岁!!!
java代码
class Solution {
public int addMinimum(String word) {
int ret = 0;
Stack<Character> stack = new Stack<>();
for (int i = 0; i < word.length(); i++) {
if (stack.isEmpty()) {
if (word.charAt(i) == 'a') {
stack.push(word.charAt(i));
} else if (word.charAt(i) == 'b') {
ret++;
stack.push(word.charAt(i));
} else {
ret += 2;
}
} else {
if (stack.peek() == 'a') {
if (word.charAt(i) == 'b') {
stack.push(word.charAt(i));
} else if (word.charAt(i) == 'c') {
ret++;
stack.pop();
} else {
ret += 2;
}
} else if (stack.peek() == 'b') {
if (word.charAt(i) == 'b') {
ret += 2;
stack.clear();
stack.push(word.charAt(i));
} else if (word.charAt(i) == 'c') {
stack.clear();
} else {
stack.clear();
stack.push(word.charAt(i));
ret++;
}
}
}
}
if (!stack.isEmpty()) {
if (stack.peek() == 'a') {
ret += 2;
} else {
ret++;
}
}
return ret;
}
}