Skip to content

Commit

Permalink
032-longest-valid-parentheses
Browse files Browse the repository at this point in the history
  • Loading branch information
bofeizhu committed Aug 14, 2018
1 parent e4ba9c4 commit 9e10d99
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 0 deletions.
33 changes: 33 additions & 0 deletions 032-longest-valid-parentheses.playground/Contents.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
/// 32. Longest Valid Parentheses
/// Given a string containing just the characters '(' and ')', find the length of the longest valid
/// (well-formed) parentheses substring.

import XCTest

/// Approach: Stack
func longestValidParentheses(_ s: String) -> Int {
var stack = [-1]
var longest = 0
for (idx, p) in s.enumerated() {
if p == "(" {
stack.append(idx)
} else {
stack.popLast()
if let last = stack.last {
longest = max(longest, idx - last)
} else {
stack.append(idx)
}
}

}
return longest
}

class Tests: XCTestCase {
func testExample() {
XCTAssertEqual(longestValidParentheses("(()"), 2)
}
}

Tests.defaultTestSuite.run()
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<playground version='5.0' target-platform='macos' executeOnSourceChanges='false'>
<timeline fileName='timeline.xctimeline'/>
</playground>
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,3 +47,4 @@
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
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
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
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 comments on commit 9e10d99

Please sign in to comment.