有效的括号字符串

题目描述

  • 给定一个字符串str,返回其最长有效括号子串的长度。

    • 有效的括号字符串是指只包含小括号,不包含其他字符,且满足括号语法规则的字符串,例如“(())”是有效的,“((a))”、“(()”、“{()}”是无效的。
    • 有效括号子串是指输入字符串中满足有效括号字符串规则的子串,例如“()(()()(”的有效括号子串包括“()”和“()()”,其最长的有效括号字串长度即为4。

分析

  • 以“()(()()(”来分析:

    • 我们先讨论匹配的情况,匹配的话对匹配个数加1。然后将括号去除,那么我们可以用栈来实现。


      这里写图片描述

    • 从左往右计算的话会出现这样的问题“(()((”,相同的字符’(‘,我们无法判断停止条件:


      这里写图片描述

    • 因而将从左往右计算改为从右往左计算:遇到’)’即入栈,有与之相配的’(‘将其出栈,匹配个数加1,要么遇到其他字符时全部出栈,匹配个数上限;若遇到’(‘字符并且栈为空时,匹配个数上限。


      这里写图片描述

总代码

#include<iostream>
#include<string>
#include<vector>
#include<stack>

using namespace std;

int calc(const string& str,int& tail) {
    stack<char> s;
    int max = 0;
    int count = 0;
    while (tail >= 0) {
        if (str[tail] == '(' && s.size() == 0 || (str[tail]!=')' && str[tail]!='(')) {
            while (s.size() != 0) {
                s.pop();
            }
            if (max < count)
                max = count;
            count = 0;
        }
        else if (str[tail] == '(' && s.top() == ')') {
            s.pop();
            ++count;
        }
        else if (str[tail] == ')') {
            s.push(str[tail]);
        }
        --tail;
    }
    if (max < count) {
        max = count;
    }
    return max*2;
}

int main(int argc, char* argv[]) {
    string str; 
    cin >> str;
    int len = str.length();
    if (len < 2)
        cout << 0 << endl;
    --len;
    cout << calc(str,len) << endl;
    getchar();
    return 0;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值