zoukankan      html  css  js  c++  java
  • [Swift]LeetCode1021. 删除最外层的括号 | Remove Outermost Parentheses

    ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
    ➤微信公众号:山青咏芝(shanqingyongzhi)
    ➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/
    ➤GitHub地址:https://github.com/strengthen/LeetCode
    ➤原文地址: https://www.cnblogs.com/strengthen/p/10667927.html 
    ➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
    ➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
    ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★

    A valid parentheses string is either empty ("")"(" + A + ")", or A + B, where A and B are valid parentheses strings, and +represents string concatenation.  For example, """()""(())()", and "(()(()))" are all valid parentheses strings.

    A valid parentheses string S is primitive if it is nonempty, and there does not exist a way to split it into S = A+B, with A and Bnonempty valid parentheses strings.

    Given a valid parentheses string S, consider its primitive decomposition: S = P_1 + P_2 + ... + P_k, where P_i are primitive valid parentheses strings.

    Return S after removing the outermost parentheses of every primitive string in the primitive decomposition of S.

    Example 1:

    Input: "(()())(())"
    Output: "()()()"
    Explanation: 
    The input string is "(()())(())", with primitive decomposition "(()())" + "(())".
    After removing outer parentheses of each part, this is "()()" + "()" = "()()()".
    

    Example 2:

    Input: "(()())(())(()(()))"
    Output: "()()()()(())"
    Explanation: 
    The input string is "(()())(())(()(()))", with primitive decomposition "(()())" + "(())" + "(()(()))".
    After removing outer parentheses of each part, this is "()()" + "()" + "()(())" = "()()()()(())".
    

    Example 3:

    Input: "()()"
    Output: ""
    Explanation: 
    The input string is "()()", with primitive decomposition "()" + "()".
    After removing outer parentheses of each part, this is "" + "" = "". 

    Note:

    1. S.length <= 10000
    2. S[i] is "(" or ")"
    3. S is a valid parentheses string

    有效括号字符串为空 ("")"(" + A + ")" 或 A + B,其中 A 和 B 都是有效的括号字符串,+ 代表字符串的连接。例如,"""()""(())()" 和 "(()(()))" 都是有效的括号字符串。

    如果有效字符串 S 非空,且不存在将其拆分为 S = A+B 的方法,我们称其为原语(primitive),其中 A 和 B 都是非空有效括号字符串。

    给出一个非空有效字符串 S,考虑将其进行原语化分解,使得:S = P_1 + P_2 + ... + P_k,其中 P_i 是有效括号字符串原语。

    对 S 进行原语化分解,删除分解中每个原语字符串的最外层括号,返回 S 。

    示例 1:

    输入:"(()())(())"
    输出:"()()()"
    解释:
    输入字符串为 "(()())(())",原语化分解得到 "(()())" + "(())",
    删除每个部分中的最外层括号后得到 "()()" + "()" = "()()()"。

    示例 2:

    输入:"(()())(())(()(()))"
    输出:"()()()()(())"
    解释:
    输入字符串为 "(()())(())(()(()))",原语化分解得到 "(()())" + "(())" + "(()(()))",
    删除每隔部分中的最外层括号后得到 "()()" + "()" + "()(())" = "()()()()(())"。
    

    示例 3:

    输入:"()()"
    输出:""
    解释:
    输入字符串为 "()()",原语化分解得到 "()" + "()",
    删除每个部分中的最外层括号后得到 "" + "" = ""。

    提示:

    1. S.length <= 10000
    2. S[i] 为 "(" 或 ")"
    3. S 是一个有效括号字符串

    24ms

     1 class Solution {
     2     func removeOuterParentheses(_ S: String) -> String {
     3         guard !S.isEmpty else { return "" }
     4         var result = [Character]()
     5         var inSub = true, backCount = 0
     6         let s = Array(S)
     7     
     8         for i in 1..<s.count {
     9             if s[i] == "(" {
    10                 if inSub {
    11                     backCount += 1
    12                     result.append("(")
    13                 } else {
    14                     inSub = true
    15                     backCount = 0
    16                 }           
    17                 continue
    18         }
    19             
    20             if s[i] == ")" {
    21                 backCount -= 1                
    22                 if backCount == -1 {
    23                     inSub = false
    24                 } else {
    25                     result.append(")")
    26                 }
    27                 continue
    28             }
    29         }
    30         return String(result)
    31      }
    32 }

    28ms

     1 class Solution {
     2     func removeOuterParentheses(_ S: String) -> String {
     3         var chars = Array(S)
     4         var count = 0
     5         var previousCount = 0
     6         var resultArray = [Character]()
     7         
     8         for i in 0..<chars.count {
     9             previousCount = count
    10             if chars[i] == "(" {
    11                 count += 1
    12             } else if chars[i] == ")" {
    13                 count -= 1
    14             }
    15             if count != 0 && previousCount != 0 {
    16                 resultArray.append(chars[i])
    17             }
    18         }
    19         let result = String(resultArray)
    20         return result
    21     }
    22 }

    32ms

     1 class Solution {
     2     func removeOuterParentheses(_ S: String) -> String
     3     {
     4         var oc = 0
     5         var temp = ""
     6         var ret = ""
     7         for c in S
     8         {
     9             if c == "(" { oc += 1 }
    10             else { oc -= 1 }
    11             
    12             temp += String(c)
    13             if oc == 0 {
    14                 ret += self.helper(temp)
    15                 temp = ""
    16             }
    17         }
    18         return ret
    19     }
    20     
    21     private func helper(_ S: String) -> String
    22     {
    23         guard S.count > 0 else { return S }
    24         
    25         var ret = S
    26         if let idx = ret.index(of: "(") { ret.remove(at: idx) }
    27         if let idx = ret.lastIndex(of: ")") { ret.remove(at: idx) }
    28         return ret
    29     }
    30 }

    36ms

     1 class Solution {
     2     func removeOuterParentheses(_ S: String) -> String {
     3         var s = S.characters.map{String($0)}
     4         var temp = [String]()
     5         var hold = ""
     6         var openCount = 0
     7         var closeCount = 0
     8         var i = 0
     9         while i < s.count{
    10             if s[i] == "("{
    11                 hold += s[i]
    12                 openCount += 1
    13             }else if hold.count != 0 && s[i] == ")"{
    14                 hold += ")"
    15                 closeCount += 1
    16             }
    17             if hold.count != 0 && closeCount == openCount{
    18                 temp.append(hold)
    19                 openCount = 0
    20                 closeCount = 0
    21                 hold = ""
    22             }
    23             i += 1
    24         }
    25         
    26         var answer = ""
    27         for pair in temp{
    28                 let startIndex  = pair.index(pair.startIndex, offsetBy: 1)
    29                 let endIndex = pair.index(pair.endIndex, offsetBy: -1)
    30                 answer += String(pair[startIndex..<endIndex])
    31         }
    32         
    33         return answer
    34     }
    35 }

    Runtime: 40 ms

    Memory Usage: 19.5 MB
     1 class Solution {
     2     func removeOuterParentheses(_ S: String) -> String {
     3         var ret:String = String()
     4         var bal:Int = 0
     5         var cur:String = String()
     6         for c in S
     7         {
     8             if c == "("
     9             {
    10                 bal += 1
    11             }
    12             else
    13             {
    14                 bal -= 1
    15             }
    16             cur.append(c)
    17             if bal == 0
    18             {
    19                 ret += cur.subString(1, cur.count - 2)
    20                 cur = String()
    21             }
    22         }
    23         return ret    
    24     }
    25 }
    26 
    27 extension String {
    28     // 截取字符串:指定索引和字符数
    29     // - begin: 开始截取处索引
    30     // - count: 截取的字符数量
    31     func subString(_ begin:Int,_ count:Int) -> String {
    32         let start = self.index(self.startIndex, offsetBy: max(0, begin))
    33         let end = self.index(self.startIndex, offsetBy:  min(self.count, begin + count))
    34         return String(self[start..<end]) 
    35     }  
    36 }

    48ms

     1 class Solution {
     2     func removeOuterParentheses(_ S: String) -> String {
     3         if S.count == 0 {
     4             return ""
     5         }
     6         var s = Array(S)
     7         var sk = [Character]()
     8         var otherSk = [Character]()
     9         var anOtherSK = [Character]()
    10         while s.isEmpty == false {
    11             if sk.isEmpty {
    12                 if anOtherSK.isEmpty {
    13                     anOtherSK.append(s.removeLast())
    14                 } else {
    15                     if s.last == "(" {
    16                         s.popLast()
    17                         anOtherSK.popLast()
    18                         continue
    19                     }
    20                 }
    21             }
    22             if sk.isEmpty && s.last == "(" {
    23                 continue
    24             }
    25             
    26             if let a = s.popLast() {
    27                 sk.append(a)
    28                 otherSk.append(a)
    29             }
    30             if sk.last == "(" {
    31                 sk.popLast()
    32                 sk.popLast()
    33             }
    34         }
    35         return String(otherSk.reversed())
    36     }
    37 }

    52ms

     1 class Solution {
     2     func removeOuterParentheses(_ S: String) -> String {
     3         let S = Array(S)
     4         var stack: [Character] = []
     5         var res: [String] = []
     6         var prev = 0
     7         for (i, ch) in S.enumerated() {
     8             if ch == "(" || ch == "[" || ch == "{" {
     9                stack.append(ch) 
    10             }
    11             
    12             if ch == ")" || ch == "}"  || ch == "]"  {
    13                 stack.remove(at: stack.count - 1)
    14             }
    15             
    16             if stack.count == 0 {
    17                res.append(String(S[prev...i]))
    18                 prev = i + 1
    19             }
    20         }
    21     
    22         return res.reduce("", {res, str in return res + String(String(str.dropFirst()).dropLast())})
    23     }
    24 }

    72ms

     1 class Solution {
     2     func removeOuterParentheses(_ S: String) -> String {
     3     let parentheses = Array(S)
     4     var groups = [[String]]()
     5     let stack = Stack<String>()
     6     var startIndex = 0
     7     var result = ""
     8     for (index, parenthese) in parentheses.enumerated() {
     9       if stack.isEmpty() && index == 0 {
    10         stack.push(String(parenthese))
    11       } else {
    12         if let element = stack.top?.element, element != String(parenthese) {
    13           stack.pop()
    14         } else {
    15           stack.push(String(parenthese))
    16         }
    17       }
    18       if stack.isEmpty() {
    19         groups.append(Array(parentheses[startIndex...index]).map{ String($0) })
    20         startIndex = index + 1
    21       }
    22     }
    23     
    24     for group in groups {
    25       let simplified = Array(group.dropFirst().dropLast())
    26       result += simplified.joined()
    27     }
    28     
    29     return result
    30   }
    31 }
    32 
    33 final class Stack<Element> {
    34   
    35   var top: Node<Element>?
    36   
    37   @discardableResult
    38   func pop() -> Element? {
    39     guard let topNode = top else { return nil }
    40     top = topNode.next
    41     return topNode.element
    42   }
    43   
    44   func push(_ element: Element) {
    45     if let topNode = top {
    46       let newTop = Node(element)
    47       newTop.next = topNode
    48       top = newTop
    49     } else {
    50       top = Node(element)
    51     }
    52   }
    53   
    54   func isEmpty() -> Bool {
    55     return top == nil
    56   }
    57 }
    58 
    59 extension Stack {
    60   
    61   final class Node<Element> {
    62     
    63     var element: Element?
    64     var next: Node<Element>?
    65     
    66     init(_ element: Element) {
    67       self.element = element
    68     }
    69   }
    70 }
  • 相关阅读:
    DIOCP开源项目详解编码器和解码器和如何在传输中加入压缩和解压功能
    DIOCP开源项目DEMO(怎么样操作远程数据库)
    网站文件更新工具
    使用Javascript正则表达式来格式化XML内容
    加载有命名空间,但没有声名的XML
    使用参数化和块语句来提高批处理SQL语句的执行效率
    让Dotnet识别Java发送来的自定义SoapHeader
    中行的EToken
    异步调用方法时异常的捕获
    使用参数化和块语句来提高批处理SQL语句的执行效率(2)
  • 原文地址:https://www.cnblogs.com/strengthen/p/10667927.html
Copyright © 2011-2022 走看看