Leetcode 227. Basic Calculator II

题目链接:https://leetcode.com/problems/basic-calculator-ii/#/description

题目描述:

mplement a basic calculator to evaluate a simple expression string.

The expression string contains only non-negative integers, +-*/ operators and empty spaces . The integer division should truncate toward zero.

You may assume that the given expression is always valid.

Some examples:

"3+2*2" = 7
" 3/2 " = 1
" 3+5 / 2 " = 5

Note: Do not use the eval built-in library function.

由于看书看到中缀表达式转后缀表达式,搜出来这个题,结果被误导了,,,想的复杂了,写了一个又长又超时的代码,思路是两个栈分别存储数字和运算符

代码1:

class Solution {
public:
    int calculate(string s) {
        if(s.length()==1)
            return s[0]-'0';
        stack<char> opr;
        stack<int> num;
        for(int i=0;i<s.length();i++)
        {
            if(s[i]>='0'&&s[i]<='9')
            {
                int tmp=s[i]-'0';
                i++;
                while(i<s.length()&&s[i]>='0'&&s[i]<='9')
                {
                    tmp=tmp*10+s[i]-'0';
                    i++;
                }
                i--;
                num.push(tmp);
            }
            else if(s[i]==' ')
                continue;
            else
            {
                if(s[i]=='*'||s[i]=='/')
                {
                     if(!opr.empty()&&(opr.top()=='*'||opr.top()=='/'))
                     {
                         while(!opr.empty())
                         {
                             if(opr.top()=='*'||opr.top()=='/')
                             {
                                calc(num,opr);
                             }
                         }
                        opr.push(s[i]);
                     }
                     else
                         opr.push(s[i]);
                }
                 
                else 
                {
                    while(!opr.empty())
                    {
                        calc(num,opr);
                    }
                    opr.push(s[i]);
                }
                
            }
        }
        while(!opr.empty())
            calc(num,opr);
        return num.top();  
    }
    void calc(stack<int> &num, stack<char>& oper )
    {
        int tmp1=num.top();
        num.pop();
        int tmp2=num.top();
        num.pop();
        if(oper.top()=='+')
        {
             num.push(tmp2+tmp1);
             oper.pop();
        }
        else if(oper.top()=='-')
        {
            num.push(tmp2-tmp1);
            oper.pop();
        }
        else if(oper.top()=='*')
        {
            num.push(tmp2*tmp1);
            oper.pop();
        }
        else
        {
            num.push(int(tmp2/tmp1));
            oper.pop();
        }
    }
};



后来搜答案,看到一个思路最简洁,代码罪简洁的http://blog.csdn.net/summer_liuwei/article/details/49383785,参考着重新写了一下,思路就是先计算乘除和减法,将每步结果压入栈中,最后再加起来

代码2:

class Solution {
public:
	int calculate(string s) {
		//先计算乘除,减当用加来计算,最后计算加
		stack<int> num_stack;//存放数字,慢一步
		int num = 0;//当前数字
		char sign = '+';
		for (int i = 0; i<s.length(); i++)
		{
			if (s[i] >= '0'&&s[i] <= '9')
			{
				num = num * 10 + s[i] - '0';
			}
			if (s[i] == ' '&&i!=s.length()-1)
				continue;
			if (s[i] == '+' || s[i] == '-' || s[i] == '*' || s[i] == '/'||i==s.length()-1)
			{
				switch (sign)
				{
				case '+':
					break;
				case '-':
					num = -num;
					break;
				case '*':
					num = num_stack.top()*num;
					num_stack.pop();
					break;
				case '/':
					num = num_stack.top() / num;
					num_stack.pop();
					break;
				default:
					break;
				}
				num_stack.push(num);
				sign = s[i];
				num = 0;
			}
		}
		//加起来
		while (!num_stack.empty())
		{
			num += num_stack.top();
			num_stack.pop();
		}
		return num;
	}
};




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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值