问题描述:
Givena string containing just the characters '('
and ')'
, find the length of the longest valid (well-formed) parenthesessubstring.
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.
问题分析:
题目即找到最长的合法字符串的长度;
见到左右括号,自然想到使用Stack进行操作;这里寻找最长的子字符串,使用一个技巧,时间复杂度为O(N),空间复杂度为O(N)
1、先遍历整个字符串,将不匹配的字符位置index push进stack;匹配的左右括号弹出;则遍历一遍后剩下的就是不匹配的字符的位置;
2、剩下的操作就是在不匹配字符之间找到最长的长度;由于每个不匹配字符的位置都已经存储到stack中,直接简单地对stack进行遍历即可;
代码:
public class Solution {
public int longestValidParentheses(String s) {
int length = s.length();
int longest = 0;
// 存储未匹配字符的位置
Stack<Integer> stack = new Stack<>();
// 先遍历一遍s,将不匹配的字符位置找出来
for (int i = 0; i < length; i++) {
// 唯一的匹配情况就是stack不为null,并且对应字符为'('与')',此情况下stack弹出,其他情况均push
if (!stack.isEmpty() && s.charAt(i) == ')' &&s.charAt(stack.peek()) == '(')
stack.pop();
else
stack.push(i);
}
// 计算每个被分割线段;即两个节点之间的数据长度
int start = 0, end = length; // 这个end可以看做尾后指针
while (!stack.isEmpty()) {
start = stack.pop();
longest = Math.max(longest,end - start - 1);
end = start;
}
// 注意不要漏下减去头前指针的情况
longest = Math.max(longest,end);
return longest;
}
}
运行结果: