四则运算表达式 - 栈模拟

发布时间 2023-11-24 05:16:08作者: 抓水母的派大星

PS:如果有更精简的写法,可以po在下面 ?

题目链接

https://www.nowcoder.com/questionTerminal/af8fddbd80f04ddc81d5658abc95ebcb

测试样例

输入:

1+5-2
1+5*3-4/2
1++1

输出:

4
14
error

注意

  1. while边界处理
#include<iostream>
using namespace std;

int main()
{
    string s="k234";
    int k1=4,k2=0;
    while((s[--k1]>='3'));
    cout<<k1<<endl; //1

    int k3=5;
    while((s[--k3]<='3'));
//        cout<<k3<<'-';
    cout<<k3<<endl; //3  先从\0开始判断

    while((s[k2++]>='2'));  // \0 = null ascii =0
    cout<<k2<<endl; //5
    return 0;
}
  1. 位数大于1的情况

解题思路

先处理乘法和除法,然后处理加减。
以pair的形式入栈,first和second访问第一个和第二个元素

代码

数据量少,不确定是否过所有后台数据

#include<iostream>
#include<stack>
using namespace std;

string parseExpression(string exp)
{
    bool flag=0;
    string s = exp;
    int l=s.length();
    for(int i=0; i<l; i++)
    {
        if(s[i]=='+'||s[i]=='-'||s[i]=='*'||s[i]=='/')
        {
            if(s[i+1]<'1' || s[i+1]>'9')
            {
                flag=1;
                break;
            }
        }
    }
    if(flag)
        return "Syntax Error";


    s="+"+s;
    l=s.length();
    bool book[1010];
    memset(book,0,sizeof(0));
    stack<pair<char,int>>S;
    for(int i=0;i<l;i++)
    {
        if(s[i]=='*' || s[i]=='/')
        {
            string s1,s2;
            int k=i;
            while(k>=1 && s[--k]>='1' && s[k]<='9')
            {
                s1+=s[k];
                book[k]=1;
            }
            reverse(s1.begin(), s1.end());
            int t1=stoi(s1);

            char opt = s[k];
            book[k]=1; // 这里的k上下while都没有进去

            k=i;
            while(s[++k]>='1' && s[k]<='9')
            {
                s2+=s[k];
                book[k]=1;
            }
            int t2=stoi(s2);

            if(s[i]=='*') S.push({opt,t1*t2});
            else if(s[i]=='/') S.push({opt,t1/t2});
//            cout<<t1<<" "<<t2<<endl;
//            cout<<opt<<(s[i]=='*'? t1*t2 : t1/t2)<<endl;

        }
    }

    // 把剩下部分 纯加减的部分压入栈
    for(int i=0;i<l;i++)
    {
        if(!book[i] && (s[i]=='+' || s[i]=='-'))
        {
            int k=i;
            string t="";
            while(s[++k]>='0' && s[k]<='9')
            {
                t+=s[k];
                book[k]=1;

            }
            int cnt=stoi(t);
            S.push({s[i],cnt});
            i=k; // 注意i=k的时候i虽然指向了正确index,但是默认的for会再给它+1,会导致跳过一个表达式
            i--;

        }
    }

    int ans=0;
    while(!S.empty())
    {
        char opt = S.top().first;
        int cnt = S.top().second;
//        cout<<opt<<" "<<cnt<<endl;
        S.pop();
        if(opt=='+') ans+=cnt;
        else ans-=cnt;

    }
    return to_string(ans);
};

int main()
{
    cout<<parseExpression("1+5-2")<<endl; // 4
    cout<<parseExpression("1+5*3-4/2")<<endl; // 14
    cout<<parseExpression("1++1")<<endl; // error

    return 0;
}