C++:栈应用:括号匹配问题(注意思考问题的方法

Leyni得到了一个由"(“和”)“组成的字符串,比如”(())()","()","(()(()))“是括号匹配的,而”)(","(()","(()))("是括号不匹配的。 为了让这个字符串括号匹配,Leyni可以去除某些括号。 他想知道,他能得到的最长的括号匹配的字符串有多长?

Input
本题有多组测试数据,输入的第一行是一个整数T代表着测试数据的数量,接下来是T组测试数据。 对于每组测试数据: 第1行 包含一个由"(“和”)"组成的非空字符串,字符串的长度不超过106。
Output
对于每组测试数据: 第1行 输出Leyni能得到的最长的括号匹配的字符串。

Sample Input
2
(()))(
((()())
Sample Output
4
6

注意方法:
读入一个字符,如果是“(”左括号,则入栈;如果是“)”右括号,则与栈(不为空)顶元素相匹配。每匹配一次,累计数量加2。

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<stack>
using namespace std;
int main()
{
    stack<char>s;
    char c;
    int t;
    scanf("%d%*c",&t);                   //注意消除换行符对下面的运算带来的影响
    while(t--)
    {
        int cnt=0;
        while(!s.empty())
            s.pop();
        while(scanf("%c",&c)!=EOF)
        {
            if(c=='\n')
                break;
            else if(c=='(')
                s.push(c);
            else if(c==')'&&!s.empty())
            {
                s.pop();
                cnt++;
            }
        }
        cnt=cnt*2;
        cout<<cnt<<endl;
    }
    return 0;
}

稍微有点不同的另一写法

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <string>
#include <cmath>
#include <queue>
#include <stack>
#include <vector>
#include <map>
#include <set>
using namespace std;
int n;
string s;
stack <int> q;
int main()
{
    cin>>n;
    while(n--)
    {
        while(!q.empty())
        {
            q.pop();
        }
        cin>>s;
        int ans=0;
        for(int i=0;i<s.size();i++)
        {
            if(s[i]=='(')
                q.push(1);
            if(s[i]==')')
            {
                if(q.empty())
                    continue;
                else
                {
                    q.pop();
                    ans+=2;
                }
            }
        }
        cout<<ans<<endl;
    }
    return 0;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值