From cea7891f69f26ce99c49d7d4711c9be285f44a4a Mon Sep 17 00:00:00 2001 From: Soap Date: Sun, 5 Jan 2020 17:57:11 -0800 Subject: [PATCH] [Stack] Refactor solution to Longest Valid Parentheses --- Stack/LongestValidParentheses.swift | 23 +++++++++++++---------- 1 file changed, 13 insertions(+), 10 deletions(-) diff --git a/Stack/LongestValidParentheses.swift b/Stack/LongestValidParentheses.swift index 50d1ced2..0c74b1f8 100644 --- a/Stack/LongestValidParentheses.swift +++ b/Stack/LongestValidParentheses.swift @@ -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 } -} \ No newline at end of file +}