题目来源:https://leetcode.com/problems/longest-valid-parentheses/
问题描述
32. Longest Valid Parentheses
Hard
Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
Example 1:
Input: "(()"
Output: 2
Explanation: The longest valid parentheses substring is "()"
Example 2:
Input: ")()())"
Output: 4
Explanation: The longest valid parentheses substring is "()()"
------------------------------------------------------------
题意
给出一个由’(‘和’)’组成的序列,求序列中最大合法括号匹配子列的长度。
------------------------------------------------------------
思路
用栈来模拟括号匹配的过程,一篇扫描过后栈中剩余的字符是无法匹配的括号,也就是合法子列之间的分隔符。另开一个栈记录这些每个字符的位置,同样模拟括号匹配的压栈弹栈过程,剩余的位置就是分隔符的位置。用迭代器遍历分隔符的位置,合并可以合并的子列,同时求出最大子列的长度。
------------------------------------------------------------
代码
class Solution {
public int longestValidParentheses(String s) {
int n = s.length(), i = 0;
Stack<Character> stack = new Stack<Character>();
Stack<Integer> pos = new Stack<Integer>();
char top = 0, cur = 0;
for (i=0; i<n; i++)
{
cur = s.charAt(i);
if (!stack.empty())
{
top = stack.peek();
if (top == '(' && cur == ')')
{
stack.pop();
pos.pop();
}
else
{
stack.push(cur);
pos.push(i);
}
}
else
{
stack.push(cur);
pos.push(i);
}
}
pos.add(n);
Iterator<Integer> iter = pos.iterator();
int pre = -1, end = -1, max_len = 0;
while (iter.hasNext())
{
end = iter.next();
max_len = (end-pre-1) > max_len ? (end-pre-1): max_len;
pre = end;
}
return max_len;
}
}