在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ Given a string Formally, a parentheses string is valid if and only if:
Given a parentheses string, return the minimum number of parentheses we must add to make the resulting string valid. Example 1: Input: 1
Example 2: Input: 3
Example 3: Input: 0
Example 4: Input: 4
Note:
给定一个由 从形式上讲,只有满足下面几点之一,括号字符串才是有效的:
给定一个括号字符串,返回为使结果字符串有效而必须添加的最少括号数。 示例 1: 输入:"())" 输出:1 示例 2: 输入:"(((" 输出:3 示例 3: 输入:"()" 输出:0 示例 4: 输入:"()))((" 输出:4 提示:
12ms:直觉与算法 跟踪字符串的平衡: 上述想法在匹配括号问题时很常见,但如果您之前没有看过,可能很难找到。 现在,考虑每个前缀的平衡 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 }
|
请发表评论