leetcode【32】Longest Valid Parentheses

问题描述:

Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.

Example 1:

Input: "(()"
Output: 2
Explanation: The longest valid parentheses substring is "()"

Example 2:

Input: ")()())"
Output: 4
Explanation: The longest valid parentheses substring is "()()"

源码:

栈方法:

用一个栈,栈顶存索引,很好解决,效率也很可以,时间上95%,空间还是100%(最近leetcode咋弄都是100%,java随便一弄就是10%以下,难道虚拟机那么占内存)

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

动态规划法:

注意从1开始遍历。时间和空间都是100%,Perfect!!!

class Solution {
public:
    int longestValidParentheses(string s) {
        int n = s.size();
        if(n==0)    return 0;
        vector<int> dp(n, 0);
        int result = 0;
        for(int i=1; i<n; i++){
            if(s[i]=='(')   dp[i] = 0;
            else{
                int index = i-dp[i-1]-1;
                if(index>=0 && s[index]=='('){
                    dp[i] = dp[i-1]+2;
                    if(index-1>=0)     dp[i]+=dp[index-1];
                }
            }
            // cout<<result<<endl;
            result = max(result, dp[i]);
        }
        return result;
    }
};

双向扫描法:

非常规做法,不做详解,效率和第一种差不多。

class Solution {
public:
    int longestValidParentheses(string s) {
        int n = s.size();
        if (n == 0) return 0;
        
        int ret = 0;
        
        // 前向扫描
        int l_cnt = 0, r_cnt = 0;
        for (int i = 0; i < n; ++i) {
            if (s[i] == '(')
                l_cnt++;
            else
                r_cnt++;
            if (l_cnt < r_cnt)
                l_cnt = r_cnt = 0;  // 而今迈步从头越
            else if (l_cnt == r_cnt)
                ret = max(ret, l_cnt * 2);
        }
        
        // 反向扫描
        l_cnt = r_cnt = 0;
        for (int i = n - 1; i >= 0; --i) {
            if (s[i] == '(')
                l_cnt++;
            else
                r_cnt++;
            if (l_cnt > r_cnt)
                l_cnt = r_cnt = 0;
            else if (l_cnt == r_cnt)
                ret = max(ret, r_cnt * 2);
        }
        
        return ret;
    }
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值