4.1.2—栈—Longest Valid Parentheses

来源:互联网 发布:男神的偶像知乎 编辑:程序博客网 时间:2024/06/16 00:31
描述
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;elseanswer = (i - mystack.top())>answer ? (i - mystack.top()) : answer;}}}return answer;}int main(){string str = "()()()())))((((()))))";int answer = ValidParenthese(str);cout << answer << endl;}

原创粉丝点击