Longest Valid Parentheses

来源:互联网 发布:图像算法工程师 知乎 编辑:程序博客网 时间:2024/06/06 08:26
#include <iostream>#include <stack>#include <string>#include <algorithm>using namespace std;/**Longest Valid ParenthesesGiven 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.思路:1.设置一个栈来保存可以待匹配的‘(’,由于只有'(' 和' )' ,所以可以简单的用if -else表示2.如果栈是空的(匹配完了上一组()情况,或者之前根本没有可以匹配的例如多个“))” ),这时设置一个last来记录最近未匹配的索引值3.如果栈非空,则计算i和sta.top()的差值找到最大长度*/class Solution {public:    int longestValidParentheses(string s) {        if(s == "")            return 0;        int maxvalid = 0;        int last = -1,i ;        stack<int> sta;        for(i=0;i < s.length();i++){            if(s[i] == '(')               sta.push(i);            else{                if(sta.empty())                    last = i;                else{                    sta.pop();                    if(sta.empty())                        maxvalid = max(maxvalid, i-last);                    else                        maxvalid = max(maxvalid,i-sta.top());                }            }        }        return maxvalid;    }};int main(){    string s = ")()()((()()()()()";    Solution sol;    int r = sol.longestValidParentheses(s);    cout << r << endl;    return 0;}

0 0
原创粉丝点击