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.
Analysis:
Key point is to save the previous result, e.g. ()(), when the second ( is scanned, the result length should add the
first pair of ().
Some special cases should be considered:
()() max = 4
(()() max = 4
()(() max = 2
We want the complexity to be O(n). Thus iteration is from the first element to the last of the string.
Stack is used to stored the character.
If current character is '(', push into the stack.
If current character is ')',
Case 1: the stack is empty, reset previous result to zero. Here we renew a pointer to store the earliest index.
Case 2: the stack is not empty, pop the top element. if the top element is '(' , (which means a () pair is found),
then if the poped stack is empty, (which means the previous pairs should be added.), len = current pos - previous pos +1; If the poped stack is not empty, len = current pos- index of stack top element.
维护上一次可能出现的左边际
Java
public class Solution {
class node{
char c1;
int index;
public node(char c1, int index) {
// TODO Auto-generated constructor stub
this.c1 = c1;
this.index = index;
}
}
public int longestValidParentheses(String s) {
int result = 0;
int len = s.length();
if(len<2) return result;
int lastLeft = 0;
Stack<node> sta = new Stack<>();
for(int i=0;i<len;i++){
if(s.charAt(i)=='('){
sta.push(new node(s.charAt(i), i));
}else {
if(!sta.empty()){
sta.pop();
if(sta.empty()){
result = Math.max(result, i-lastLeft+1);
}else {
result = Math.max(result, i-sta.lastElement().index);
}
}else {
lastLeft = i+1;
}
}
}
return result;
}
}c++
int longestValidParentheses(string s) {
int result = 0;
int lastleft = 0;
if(s.size()<2) return result;
stack<int> sta;
for(int i=0; i<s.size(); i++){
if(s[i]=='('){
sta.push(i);
}
else{
if(!sta.empty()){
sta.pop();
if(!sta.empty())
result = max(result, i-sta.top());
else
result = max(result,i-lastleft+1);
}else{
lastleft = i+1;
}
}
}
return result;
}

本文介绍了一种高效算法来寻找字符串中最长的有效括号子串。通过使用栈记录左括号的位置,并在遇到右括号时计算已配对括号的长度,实现了O(n)的时间复杂度。
145

被折叠的 条评论
为什么被折叠?



