题目
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.
思路
栈中保存的不是字符(而是字符(所在的下标。
如果遇到字符(,无条件压入栈中;
如果遇到字符),并且栈为空,说明这是一个无法匹配的字符),用变量last记录下标。last存放的其实是最后一个无法匹配的字符)。
如果遇到字符),并且栈不为空,我们可以消除一对括号(栈顶元素出栈)。
代码
/*---------------------------------------------------------
* 日期:2015-04-23
* 作者:SJF0115
* 题目: 32.Longest Valid Parentheses
* 网址:https://leetcode.com/problems/longest-valid-parentheses/
* 结果:AC
* 来源:LeetCode
* 博客:
------------------------------------------------------------*/
#include <iostream>
#include <vector>
#include <stack>
using namespace std;
class Solution {
public:
int longestValidParentheses(string s) {
int size = s.size();
if(size <= 1){
return 0;
}//if
int last = -1;
int Max = 0;
stack<int> leftStack;
for(int i = 0;i < size;++i){
// (入栈
if(s[i] == ‘(‘){
leftStack.push(i);
}//if
else if(s[i] == ‘)‘){
if(leftStack.empty()){
last = i;
}//if
else{
leftStack.pop();
if(leftStack.empty()){
Max = max(Max,i - last);
}//if
else{
Max = max(Max,i - leftStack.top());
}//else
}//else
}//else
}//for
return Max;
}
};
int main(){
Solution solution;
string str("()(()");
cout<<solution.longestValidParentheses(str)<<endl;
return 0;
}
运行时间
[LeetCode]32.Longest Valid Parentheses
原文地址:http://blog.csdn.net/sunnyyoona/article/details/45226477