leetcode problem 32 -- Longest Valid Parentheses

Longest Valid Parentheses

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.

 

 

思路1:

  从左到右依次扫描,用一个数组v记录括号是否已经匹配。然后再扫描一次v,用一个变量count记录连续合法括号数目。如果v[i] = 0则说明该括号未匹配,合法括号序列终端,count = 0. 代码如下:

Runtime: 22 ms

class Solution {
public:
    int longestValidParentheses(string s) {
        vector<int> v(s.length(), 0);
        stack<int> stac;
        for (int i = 0; i < s.length(); ++i) {
            if (s[i] == ')') {
                if (stac.empty())
                    continue;
                else {
                    v[i] = 2;
                    v[stac.top()] = 2;
                    stac.pop();
                }
            }
            else 
                stac.push(i);
        }

        int res = 0, count = 0;
        for (int i = 0; i < s.length(); ++i) {
            if (v[i] == 0) {
                if (res < count)
                    res = count;
                count = 0;
            }
            else if (s[i] == '(')
                count += v[i];
        }
        return res < count ? count : res;
    }

};

 

思路二:

  先从左到右扫描,分别记录'('和')'的数目, 如果一旦')'的数目大于'(' 那么可以确定合法连续括号序列中断。记录countMax。  

  然后从右往左扫描,同样分别记录'('和')'的数目, 如果一旦'('的数目大于')' , 那么可以确定合法连续括号序列中断。记录countMax。  

代码如下:

Runtime: 10 ms

class Solution {
public:
    int longestValidParentheses(string s) {
        int ll = 0, lr = 0, li = 0;    
        int rl = 0, rr = 0, ri = s.length()-1;
        int res = 0;
        for (; li < s.length() && ri >= 0; ++li, --ri) {
            switch (s[li]) {
                case '(':
                    ++ll;
                    break;
                case ')':
                    ++lr;
            }
            switch (s[ri]) {
                case '(':
                    ++rl;
                    break;
                case ')':
                    ++rr;
            }
            if (ll == lr && (ll * 2) > res) 
                res = 2 * ll;
            else if (ll < lr)
                ll = lr = 0;
            
            if (rl == rr && (rl * 2) > res) 
                res = 2 * rl;
            else if (rl > rr)
                rl = rr = 0;
            
        }
        
        return res;
    }
private:

};

 

posted on 2015-04-20 17:35  lysuns  阅读(158)  评论(0编辑  收藏  举报

导航