【无标题】

文章介绍了使用栈解决括号匹配问题和后缀表达式计算的方法。在括号匹配问题中,通过入栈和出栈操作检查字符串中的括号是否匹配;在后缀表达式问题中,栈被用来存储数值和运算符,进行逆波兰表示法的计算。此外,还讨论了判断给定出栈序列是否合法的问题。
摘要由CSDN通过智能技术生成

18933 括号匹配问题

#include <iostream>
#include <cstring>
#include <stack>
#include <string.h>
using namespace std;
typedef pair<int,int> PII;
const int N = 100010;
stack<int> s;
char str[N];
char ans[N];
int main()
{
    while(scanf("%s",str)!=EOF)
    {
        int len = strlen(str);
        for(int i = 0 ; i < len ; i ++)
        {
            if(str[i]=='(')
            {
                s.push(i);
                ans[i]=' ';
            }
            else if(str[i]==')')
            {
                if(!s.empty())
                {
                    s.pop();
                    ans[i]=' ';
                }
                else ans[i] = '?';
            }
            else ans[i]=' ';
        }
        ans[len]='\0';
        while(!s.empty())
        {
            int t = s.top();
            ans[t] = '$';
            s.pop();
        }
        puts(str);
        puts(ans);
    }

}

19009 后缀表达式
#include <iostream>
#include <cstring>
#include <stack>
#include <string.h>
using namespace std;
const int N = 100010;
stack<int> s;
char str[N];
char a[N];
void eval(char ch)
{
    int b = s.top();
    s.pop();
    int a = s.top();
    s.pop();
    int x;
    if(ch=='+') s.push(a+b);
    else if(ch=='-') s.push(a-b);
    else if(ch=='*') s.push(a*b);
    else s.push(a/b);
}
int main()
{
    char ch='0';
    ch = getchar();
    while(ch!='@')
    {
        if(ch-'0'>=0&&ch-'0'<10) s.push(ch-'0');
        else if(ch==' ') ch='1';
        else eval(ch);
        ch = getchar();
    }
    cout<<s.top();
}

18932 出栈序列合法性判定

#include <iostream>
#include <cstring>
#include <stack>
#include <string.h>
using namespace std;
const int N = 100010;
int a[N],b[N];
stack<int> s;
int n;
int main()
{
    cin>>n;
    for(int i = 1 ; i <= n ; i ++) cin>>a[i];
    for(int i = 1 ; i <= n ; i ++) cin>>b[i];
    int i = 1 , k = 1;
    while(k<=n)
    {
        if(i<=n)
        {
            if(a[i]!=b[k]) s.push(a[i++]);
            else
            {
                i++;
                k++;
            }
        }
        else
        {
            if(s.top()==b[k++]) s.pop();
            else
            {
                cout<<"no";
                return 0;
            }
        }
    }
    cout<<"yes";
}
18715 出栈序列_sigd的博客-CSDN博客

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值