【leetcode】921. Minimum Add to Make Parentheses Valid
英文题目:
Given a string S of ‘(’ and ‘)’ parentheses, we add the minimum number of parentheses ( ‘(’ or ‘)’, and in any positions ) so that the resulting parentheses string is valid.
Formally, a parentheses string is valid if and only if:
·It is the empty string, or
·It can be written as AB (A concatenated with B), where A and B are valid ·strings, or
It can be written as (A), where A is a valid string.
Given a parentheses string, return the minimum number of parentheses we must add to make the resulting string valid.
中文释义:题目给你一个字符串,根据括号匹配的规则找出不能正常匹配的括号的个数,例如,“()()”这个就是正常匹配,但是“())”这个就不能正常匹配,最右边的右括号缺少一个左括号来匹配。
Example 1:
Input: “())”
Output: 1
Example2:
Input: “(((”
Output: 3
Example3:
Input: “()”
Output: 0
Example 4:
Input: “()))((”
Output: 4
解题思路
括号匹配一般用的都是栈这种数据结构,这题也是用栈来解决,首先我们可以分两部分来解决这个问题,先将字符串转为字符数组,然后遍历字符数组。1、若栈为空,该字符直接入栈。2、若栈不为空,且字符为“(”,直接入栈,再判断栈顶是否有“)”,这些前面“)”都是不能匹配的右括号,用while循环出栈,直到栈顶不为“)”,出栈一个未匹配的数量就加1。3、遇到字符为“)”,就先判断栈顶是否为“(”,若是,则出栈,若不是,则“)”入栈。4、遍历完字符数组后,再计算栈的长度,此时栈内剩下的元素都是没有匹配的括号。
源代码(java)
代码片
.
public int minAddToMakeValid(String S) {
char[] chars = S.toCharArray();
int result = 0;
Stack<Character> stack = new Stack<Character>();
for (int i = 0; i < chars.length; i++) {
//若栈为空,直接入栈
if (stack.empty()) {
stack.push(chars[i]);
} else {
//遇到左括号
if (chars[i] == '(') {
//直接入栈
stack.push(chars[i]);
//判断栈顶是否有")"
if (stack.peek() == ')') {
//有就出栈,直到栈空或者栈顶元素不是")"
while (!stack.empty() && stack.peek() != ')') {
stack.pop();
result++;
}
}
//左括号入栈
}
//遇到右括号
if (chars[i] == ')') {
//判断栈顶是否有"(",有就出栈
if (stack.peek() == '(') {
stack.pop();
}
//栈顶不是"(",右括号进栈
else {
stack.push(chars[i]);
}
}
}
}
//遍历栈内还有未匹配的括号
while (!stack.empty()) {
stack.pop();
result++;
}
return result;
}