問題: 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