Tuesday, October 27, 2015

Longest Valid Parentheses

Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
For "(()", the longest valid parentheses substring is "()", which has length = 2.
Another example is ")()())", where the longest valid parentheses substring is "()()", which has length = 4.
思路:
1. 使用一个和字符串等长的数组,初始化为0。
2. 使用堆栈存放左括号,如果为 '(' 则压入 '(' 所在位置index。
3. 如果是 ')' 且堆栈不为空,则在数组中设置栈顶左括号的位置和当前右括号的位置的值为1. 弹出栈顶。
4. 此时数组中只有0和1,合法的括号,一定是连续的1. 此题变为最大子序列和。为1计算,为0清零。

No comments:

Post a Comment