Skip to content

Commit

Permalink
[Stack] Refactor solution to Longest Valid Parentheses
Browse files Browse the repository at this point in the history
  • Loading branch information
soapyigu authored Jan 6, 2020
1 parent 301c6df commit cea7891
Showing 1 changed file with 13 additions and 10 deletions.
23 changes: 13 additions & 10 deletions Stack/LongestValidParentheses.swift
Original file line number Diff line number Diff line change
Expand Up @@ -6,23 +6,26 @@

class LongestValidParentheses {
func longestValidParentheses(_ s: String) -> Int {
let sChars = Array(s.characters)
var stack = [Int]()
var longest = 0
var stack = [Int](), longest = 0, start = 0

for (i, char) in sChars.enumerated() {
if char == "(" || stack.isEmpty || sChars[stack.last!] == ")" {
for (i, char) in s.enumerated() {
if char == "(" {
stack.append(i)
} else {
let _ = stack.removeLast()
if stack.isEmpty {
longest = max(longest, i + 1)
if !stack.isEmpty {
stack.removeLast()

if let last = stack.last {
longest = max(longest, i - last)
} else {
longest = max(longest, i - start + 1)
}
} else {
longest = max(longest, i - stack.last!)
start = i + 1
}
}
}

return longest
}
}
}

0 comments on commit cea7891

Please sign in to comment.