[leetcode]longest Valid Parentheses(!!)

来源:互联网 发布:java多线程单例 编辑:程序博客网 时间:2024/05/02 00:23


class Solution {public:    int longestValidParentheses(string s) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        int nSize = s.size();        int max = 0;        int begin = nSize;// where a part of legal parentheses begin        stack<int> stk;        for(int i = 0; i< nSize; ++i){            if(s[i] == '('){                stk.push(i);            }            else if(!stk.empty()){                int tmp = stk.top();                stk.pop();                begin = begin < tmp ? begin : tmp;                if(stk.empty())                    max = max > i - begin + 1 ? max : i - begin +1;                else                    max = max > i - stk.top()? max : i - stk.top();            }            else{                begin = i + 1;            }        }        return max;    }};

充分利用了begin 和stk.top这个两个信息!!!