// "(" 进栈
// ")" 两种情况: 栈为空, 所以必须加个"("
// 栈不为空, 是否匹配的上
class Solution {
public boolean match(char a, char b) {
if (a == '(' && b == ')')
return true;
return false;
}
public int minAddToMakeValid(String s) {
ArrayDeque<Character> stack = new ArrayDeque<>();
int cnt = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '(') {
stack.addLast(s.charAt(i));
}else {
if (stack.isEmpty()){
cnt++;
continue;
}
char c = stack.pollLast();
if (!match(c, s.charAt(i))) {
cnt += 2;
}
}
}
if (!stack.isEmpty())
cnt += stack.size();
return cnt;
}
}
921. 使括号有效的最少添加 栈
最新推荐文章于 2022-10-04 21:19:26 发布