问题描述:
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.
题意比较直白,找到一个字符串中最长的合法括号子串。
解题思路:
官方有给出解答,我自己想到的方法是用一个堆栈存储左括号在字符串中的位置,每次匹配到右括号时,用一个 HashMap字典保存左右括号的位置。但这种方法还需要再次遍历一遍字典,从而导致最后 Time Limit Exceeded.
官方的解答中也用了堆栈的方法,不同的是会在栈底添加上一次违反括号匹配规则的右括号位置。
Java 实现:
class Solution {
public int longestValidParentheses(String s) {
LinkedList<Integer> stack = new LinkedList<>();
stack.push(-1);
int maxLen = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '(') {
stack.push(i);
} else {
if (!stack.isEmpty()) {
stack.pop();
if (stack.isEmpty()) {
stack.push(i);
} else {
maxLen = Math.max(i - stack.peekFirst(), maxLen);
}
}
}
}
return maxLen;
}
}