[Swift]LeetCode921.使括號有效的最少添加 | Minimum Add to Make Parentheses Valid

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-tqctjnjw-me.html 
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html

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.git

Formally, a parentheses string is valid if and only if:github

  • 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 

Example 2:app

Input: "((("
Output: 3 

Example 3:spa

Input: "()"
Output: 0 

Example 4:code

Input: "()))(("
Output: 4

 Note:orm

  1. S.length <= 1000
  2. S only consists of '(' and ')' characters.

給定一個由 '(' 和 ')' 括號組成的字符串 S,咱們須要添加最少的括號( '(' 或是 ')',能夠在任何位置),以使獲得的括號字符串有效。htm

從形式上講,只有知足下面幾點之一,括號字符串纔是有效的:

  • 它是一個空字符串,或者
  • 它能夠被寫成 AB (A 與 B 鏈接), 其中 A 和 B 都是有效字符串,或者
  • 它能夠被寫做 (A),其中 A 是有效字符串。

給定一個括號字符串,返回爲使結果字符串有效而必須添加的最少括號數。

 示例 1:

輸入:"())"
輸出:1

示例 2:

輸入:"((("
輸出:3

示例 3:

輸入:"()"
輸出:0

示例 4:

輸入:"()))(("
輸出:4

提示:

  1. S.length <= 1000
  2. S 只包含 '(' 和 ')' 字符。

 12ms:直覺與算法

跟蹤字符串的平衡:'(''s的數量減去's的數量')'。若是字符串的平衡爲0,則該字符串有效,而且每一個前綴都具備非負平衡。

上述想法在匹配括號問題時很常見,但若是您以前沒有看過,可能很難找到。

如今,考慮每一個前綴的平衡S。若是它是負數(好比-1),咱們必須添加一個'('括號。另外,若是平衡S是正數(比方說+B),咱們必須B在末尾添加')'括號。

 1 class Solution {
 2     func minAddToMakeValid(_ S: String) -> Int {
 3         var ans:Int = 0 , bal:Int = 0
 4         for index in S.indices
 5         {
 6             bal += S[index] == "(" ? 1 : -1
 7             if bal == -1
 8             {
 9                 ans += 1
10                 bal += 1
11             }
12         }
13         return ans + bal
14     }
15 }

16ms

 1 class Solution {
 2     func minAddToMakeValid(_ S: String) -> Int {
 3         var incompleteSymbols: [Character] = []
 4         
 5         S.forEach { character in
 6             if let lastIncomplete = incompleteSymbols.last {
 7                 if lastIncomplete == "(" && character == ")" {
 8                     incompleteSymbols.removeLast()
 9                 }
10                 else {
11                     incompleteSymbols.append(character)
12                 }
13             }
14             else {
15                 incompleteSymbols.append(character)
16             }
17         }
18         
19         return incompleteSymbols.count
20     }
21 }

20ms

 1 class Solution {
 2     func minAddToMakeValid(_ S: String) -> Int {
 3         if(S == ""){
 4             return 0
 5         }
 6         
 7         var arrS = Array(S).map{"\($0)"}
 8         var open = 0
 9         var unclosed = 0
10         for c in arrS {
11             if(c == "(") { 
12                 open += 1 
13             }
14             if(c == ")") { 
15                 if( open > 0){
16                     open -= 1
17                 } else {
18                     unclosed += 1
19               }
20             }
21         }
22         var total = (open + unclosed)
23         return total 
24     }
25 }

20ms

 1 class Solution {
 2     func minAddToMakeValid(_ S: String) -> Int {
 3         var arr = [Character]()
 4         S.forEach { (c) in
 5              if arr.count>0 &&  arr[arr.count-1] == "(" && c == ")" {
 6                 arr.removeLast()
 7             } else { arr.append(c) }
 8         }
 9         return arr.count
10     }
11 }

64ms

 1 class Solution {
 2     func minAddToMakeValid(_ S: String) -> Int {
 3         var stack = [String]()
 4         
 5         for i in 0..<S.count {
 6             if S[i] == "(" {
 7                 stack.append(S[i])
 8             } else if S[i] == ")" && stack.last == "(" {
 9                 stack.removeLast()
10             } else {
11                 stack.append(S[i])
12             }
13         }
14         
15         return stack.count
16     }
17 }
18 
19 extension String {
20     subscript(i:Int) -> String {
21         let charIndex = self.index(self.startIndex, offsetBy: i)
22         return String(self[charIndex])
23     }
24 }
相關文章
相關標籤/搜索