leetcode Basic Calculator 栈

Implement a basic calculator to evaluate a simple expression string.

The expression string may contain open ( and closing parentheses ), the plus + or minus sign -non-negative integers and empty spaces .

You may assume that the given expression is always valid.

Some examples:

"1 + 1" = 2
" 2-1 + 2 " = 3
"(1+(4+5+2)-3)+(6+8)" = 23

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

题目很容易懂,就是实现个计算功能,肯定是用栈,刚开始没仔细思考,凭感觉写了,结果各种用例错误,囧,比如空格,多位整数可以先存在string中,然后转int,还有就是因为是从左到右结合的倒着入栈比较好,比如2-1+3,如果先把2入栈,那直接倒着出来的时候就是3+1-2,肯定是错的,就得加入很多判断,但是倒着入栈顺序就是一致的,先计算2-1,再+3.这里用了两个栈,一个存符号,一个存数字,计算+-的时候从数字数组中pop两个,运算完再push回去。

class Solution {
public:
	//一定要倒着插,如果正着插比如2-1+2则不好运算。
	int calculate(string s) {
		int newnum = 0;
		int res=0;
		stack<int>num;//存数字的
		stack<char>S;//存运算符
		string str;
		s = s + ')'; //碰见'('才计算,所以需要在最外面加'()'
		s = '(' + s;
		for (int i = s.size()-1; i >=0; i--)//倒着入栈
		{
			if (s[i] == '-' || s[i] == '+')
			{
				S.push(s[i]);
				if (str.size() != 0)
				{
					res = atoi(str.c_str());//str转int
					num.push(res);
					str.clear();
				}
			}
			else if (s[i] == '(')//碰见(进行计算
			{
				if (str.size()!=0)//(前面还有值的话
				{
					res = atoi(str.c_str());
					num.push(res);
					str.clear();
				}
				while (!S.empty() && S.top() != '(')//碰到(则停止
				{
					if (S.top() == '+' || S.top() == '-')
					{
						res = num.top();
						num.pop();
						newnum = num.top();
						num.pop();
						(S.top() == '+') ? res = res + newnum : res = res - newnum;
						num.push(res);
						S.pop();//弹出+ 或-
					}
					else
					{
						S.pop();//弹出)
						break;
					}
					
				}
			}
			else if (s[i] == ')')
			{
				S.push(')');
			}
			else
			{
				if (s[i] != ' ') str = s[i] + str;//把符号之间的数存在string里
				
			}
		}
		return num.top();
	}
};


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值