问题: 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.java
Example 1:
Input: "())"
Output: 1
Example 2:
Input: "((("
Output: 3
Example 3:
Input: "()"
Output: 0
Example 4:
Input: "()))(("
Output: 4
Note:
S.length <= 1000
S only consists of '(' and ')' characters.
复制代码
方法: 像这种左右对称的算法题主要经过栈去处理,遇到成对的"()"就从栈中pop,最后剩下的就是没有成对的,也就是题目要计算的数量。git
具体实现:github
import java.util.*
class MinimumAddToMakeParenthesesValid {
fun minAddToMakeValid(S: String): Int {
val stack = ArrayDeque<Char>()
for (ch in S) {
if (stack.isEmpty()) {
stack.push(ch)
continue
}
if (ch == ')' && stack.first == '(') {
stack.pop()
} else {
stack.push(ch)
}
}
return stack.size
}
}
fun main(args: Array<String>) {
val input = "())"
val minimumAddToMakeParenthesesValid = MinimumAddToMakeParenthesesValid()
println(minimumAddToMakeParenthesesValid.minAddToMakeValid(input))
}
复制代码
有问题随时沟通算法
具体代码实现能够参考Githubbash