Longest Valid Parentheses

 方法:在栈中直接记录字符串的下标更加方便

class Solution {
public:
    int longestValidParentheses(string s) {
        int maxLen = 0, last = -1;
        stack<int> ss;
        
        for(int i=0; i<s.size(); ++i)
        {
            if(s[i] == '(')
                ss.push(i);
            else
            {
                if(ss.empty())
                {
                    last = i;
                }
                else
                {
                    ss.pop();
                    if(ss.empty())
                        maxLen = max(maxLen, i - last);
                    else
                        maxLen = max(maxLen, i-ss.top());
                }
            }
        }
        
        return maxLen;
    }
};

 

posted @ 2017-04-30 09:50  chengcy  Views(90)  Comments(0)    收藏  举报