Longest Valid Parentheses

Longest Valid Parentheses

题目大意

给你一个括号构成的字符串,检测其中合法的最长的字符串。如”)()())”,则结果为4.

我的解法

解题思路

使用一个栈来处理字符串,左括号’(‘进栈,右括号’)’出栈。合法字符串被不合法字符串隔开,这种不合法字符串有两种。
第一种是栈为空的时候,进入的右括号。
第二种是字符串结束时,没有出栈的左括号。
程序最后要将不合法字符的下标存在栈中,再遍历栈计算长度。

代码
class Solution {
public:
    int longestValidParentheses(string s) {
        stack<int> st;
        int stack_down = 0;
        for(int i=0; i<s.length(); i++)
        {
            if(s[i]=='(')
            {
                st.push(i);
            }
            else if(st.size()>stack_down)
            {
                st.pop();
            }
            else
            {
                st.push(i);
                stack_down++;
            }
        }
        if(st.empty())
        {
            return s.length();
        }
        int max = 0;
        int pop = s.length();
        while(!st.empty())
        {
            int count = pop - st.top()-1;
            pop = st.top();
            st.pop();
            if(count>max)
            {
                max = count;
            }
        }
        if(pop > max)
            max = pop;
        return max;
    }
};

优解

解题思路

基本一致,但是代码更简练一些

代码
class Solution {
public:
    int longestValidParentheses(string s) {
        int n = s.length(), longest = 0;
        stack<int> st;
        for (int i = 0; i < n; i++) {
            if (s[i] == '(') st.push(i);
            else {
                if (!st.empty()) {
                    if (s[st.top()] == '(') st.pop();
                    else st.push(i);
                }
                else st.push(i);
            }
        }
        if (st.empty()) longest = n;
        else {
            int a = n, b = 0;
            while (!st.empty()) {
                b = st.top(); st.pop();
                longest = max(longest, a-b-1);
                a = b;
            }
            longest = max(longest, a);
        }
        return longest;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值