Skip to content

Commit 9e10d99

Browse files
committed
032-longest-valid-parentheses
1 parent e4ba9c4 commit 9e10d99

File tree

3 files changed

+38
-0
lines changed

3 files changed

+38
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/// 32. Longest Valid Parentheses
2+
/// Given a string containing just the characters '(' and ')', find the length of the longest valid
3+
/// (well-formed) parentheses substring.
4+
5+
import XCTest
6+
7+
/// Approach: Stack
8+
func longestValidParentheses(_ s: String) -> Int {
9+
var stack = [-1]
10+
var longest = 0
11+
for (idx, p) in s.enumerated() {
12+
if p == "(" {
13+
stack.append(idx)
14+
} else {
15+
stack.popLast()
16+
if let last = stack.last {
17+
longest = max(longest, idx - last)
18+
} else {
19+
stack.append(idx)
20+
}
21+
}
22+
23+
}
24+
return longest
25+
}
26+
27+
class Tests: XCTestCase {
28+
func testExample() {
29+
XCTAssertEqual(longestValidParentheses("(()"), 2)
30+
}
31+
}
32+
33+
Tests.defaultTestSuite.run()
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
2+
<playground version='5.0' target-platform='macos' executeOnSourceChanges='false'>
3+
<timeline fileName='timeline.xctimeline'/>
4+
</playground>

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,3 +47,4 @@
4747
29 | [Divide Two Integers](https://leetcode.com/problems/divide-two-integers/description/) | [Solution](https://github.com/zhubofei/LeetCode-Swift/blob/master/029-divide-two-integers.playground/Contents.swift) | String
4848
30 | [Substring with Concatenation of All Words](https://leetcode.com/problems/substring-with-concatenation-of-all-words/description/) | [Solution](https://github.com/zhubofei/LeetCode-Swift/blob/master/030-substring-with-concatenation-of-all-words.playground/Contents.swift) | Two Pointers
4949
31 | [Next Permutation](https://leetcode.com/problems/next-permutation/description/) | [Solution](https://github.com/zhubofei/LeetCode-Swift/blob/master/031-next-permutation.playground/Contents.swift) | Two Pointers
50+
32 | [Longest Valid Parentheses](https://leetcode.com/problems/longest-valid-parentheses/description/) | [Solution](https://github.com/zhubofei/LeetCode-Swift/blob/master/032-longest-valid-parentheses.playground/Contents.swift) | Stack

0 commit comments

Comments
 (0)