描述
Given a string containing just the characters ’(’ and ’)’, find the length of the longest valid (wellformed) 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.
Given a string containing just the characters ’(’ and ’)’, find the length of the longest valid (wellformed) 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.
#include <iostream>
#include <string>
#include<vector>
#include <stack>
using namespace std;
int ValidParenthese(string str)
{
int answer = 0;
int last = -1;
int length = str.size();
stack<int> mystack;
for (int i = 0; i<length; i++)
{
if (str[i] == '(')
mystack.push(i);
else if (str[i] == ')')
{
if (mystack.empty())
{
last = i;
}
//===
else
{
mystack.pop();
if (mystack.empty())
answer = (i - last)>answer ? (i - last) : answer;
else
answer = (i - mystack.top())>answer ? (i - mystack.top()) : answer;
}
}
}
return answer;
}
int main()
{
string str = "()()()())))((((()))))";
int answer = ValidParenthese(str);
cout << answer << endl;
}