zoukankan      html  css  js  c++  java
  • LeetCode 224. Basic Calculator

    题目

    题解:后缀表达式一把嗦

    class Solution {
    public:
        string s1[1000005];
        string s2[1000005];
        int s3[1000005];
        int top1;
        int top2;
        int top3;
        int calculate(string s) {
            
            top1=0;top2=0;top3=0;
            string str="";
            for(int i=0;i<s.length();i++)
            {
                if(s[i]>='0'&&s[i]<='9')
                {
                    str+=s[i];
                    continue;
                }
                
                if(str!="")
                {
                    s2[top2++] = str;
                    str="";
                }
                if(s[i]==' ') continue;
                
                if(s[i]=='(')
                {
                    s1[top1++] = s[i];
                }
                else if(s[i]=='+'||s[i]=='-')
                {
                    if(top1==0||s1[top1-1]=="(")
                    {
                        s1[top1++]=s[i];
                    }
                    else
                    {
                        s2[top2++]=s1[top1-1];
                        top1--;
                        
                        s1[top1++]=s[i];
                    } 
                }
                else if(s[i]==')')
                {
                    if(s1[top1-1]!="(")
                    {
                        s2[top2++]=s1[top1-1];
                        top1-=2;
                    }
                    else
                    {
                        top1--;
                    }
                }
            }
            
            if(str!="")
                s2[top2++]=str;
            
            while(top1!=0)
            {
                s2[top2++]=s1[top1-1];
                top1--;
            }
            
            for(int i=0;i<top2;i++)
            {
                if(s2[i]=="+")
                {
                    int x =s3[top3-2]+s3[top3-1];
                    top3-=2;
                    s3[top3++]=x;
                }
                else if(s2[i]=="-")
                {
                    int x =s3[top3-2]-s3[top3-1];
                    top3-=2;
                    s3[top3++]=x;
                }
                else
                {
                    s3[top3++]=atoi(s2[i].c_str());
                }
            }
            
            return s3[0];
            
        }
    };
    
  • 相关阅读:
    第九周总结
    第八周总结
    第六周
    中国历史上成功的两个人
    第五周总结
    第四周总结
    关于IT行业的抄袭事件
    第三周总结
    第二周总结
    第九周
  • 原文地址:https://www.cnblogs.com/dacc123/p/12350373.html
Copyright © 2011-2022 走看看