码迷,mamicode.com
首页 > 其他好文 > 详细

Longest Valid Parentheses

时间:2016-02-06 22:22:13      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:

Given 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.

 

Subscribe to see which companies asked this question

Show Tags
Show Similar Problems
 
class Solution {
public:
    int longestValidParentheses(string s) {
        int length = s.length();
        if (0 == length) {
            return 0;
        }
        int max_len = 0;
        int i = 0;
        int start = 0;
        stack<int> s_i;
        for (i=0; i<length; i++) {
            if (s[i] == () {
                s_i.push(i);
            } else if (s[i] == ) && !s_i.empty()) {
                //int left = s_i.top();
                s_i.pop();
                if (s_i.empty()) {
                    max_len = max(max_len, i - start + 1);
                } else {

                    max_len = max(max_len, i - s_i.top());
                    cout << "max len when not empty is " << max_len << endl;
                }
            } else {
                start = i + 1;
            }
        }
        return max_len;
    }
};

 

Longest Valid Parentheses

标签:

原文地址:http://www.cnblogs.com/SpeakSoftlyLove/p/5184352.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!