From b2de726a4fdb1d7f44080f42690bec9a4adbb137 Mon Sep 17 00:00:00 2001 From: JeffLiu Date: Sat, 18 Jul 2020 23:05:51 +0800 Subject: [PATCH] [Stack] Add a solution to Longest Valid Parentheses --- Stack/LongestValidParentheses.swift | 43 +++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/Stack/LongestValidParentheses.swift b/Stack/LongestValidParentheses.swift index 0c74b1f8..6e6a0c87 100644 --- a/Stack/LongestValidParentheses.swift +++ b/Stack/LongestValidParentheses.swift @@ -29,3 +29,46 @@ class LongestValidParentheses { return longest } } + + +class LongestValidParenthesesWithoutExtraSpace { + func longestValidParentheses(_ s: String) -> Int { + var longest = 0, leftCount = 0, rightCount = 0 + + for char in s { + if char == "(" { + leftCount += 1 + } else { + rightCount += 1 + } + + if leftCount == rightCount { + longest = max(longest, leftCount + rightCount) + } else if leftCount < rightCount { + leftCount = 0 + rightCount = 0 + } + } + + leftCount = 0 + rightCount = 0 + + for char in s.reversed() { + if char == "(" { + leftCount += 1 + } else { + rightCount += 1 + } + + if leftCount == rightCount { + longest = max(longest, leftCount + rightCount) + } else if leftCount > rightCount { + leftCount = 0 + rightCount = 0 + } + } + + return longest + } +} +