[LeetCode] Longest Valid Parentheses

来源:互联网 发布:网页美工设计视频 编辑:程序博客网 时间:2024/06/07 02:52
[Problem]

Given a string containing just the characters '('and ')', find the length of the longest valid(well-formed) parentheses substring.

For "(()", the longest valid parentheses substringis "()", which has length = 2.

Another example is ")()())", where the longestvalid parentheses substring is "()()", which haslength = 4.


[Analysis]

注意是最长的合法圆括号,()(() 存在合法圆括号有4个,前面2个,后面2个,但是连续最长的是2个。同样,)()())()()(存在合法圆括号有8个,下标为1,2,3,4,6,7,8,9,但是连续最长的是1,2,3,4或者6,7,8,9,最长的是4个。
开始没看清楚题,以为是求合法圆括号总个数,一直WA。

[Solution]

class Solution {
public:
int longestValidParentheses(string s) {
// Start typing your C/C++ solution below
// DO NOT write int main() function

int len = s.length();
stack<int> myStack;
for(int i = 0; i < len; ++i){
if(s[i] == '('){
myStack.push(i);
}
else if(s[i] == ')'){
if(myStack.size() <= 0 || s[myStack.top()] != '('){
myStack.push(i);
}
else{
myStack.pop();
}
}
}

// all of the parentheses are valid
if(myStack.empty()){
return len;
}

// search the longest valid parentheses
int max = len-1-myStack.top();
while(!myStack.empty()){
int top = myStack.top();
myStack.pop();
if(!myStack.empty()){
int len = top - myStack.top() - 1;
max = max > len ? max : len;
}
else{
max = max > top ? max : top;
}
}
return max;
}
};


 说明:版权所有,转载请注明出处。Coder007的博客
原创粉丝点击