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 .

Example 1:

Input: "1 + 1"
Output: 2

Example 2:

Input: " 2-1 + 2 "
Output: 3

Example 3:

Input: "(1+(4+5+2)-3)+(6+8)"
Output: 23

Note:

  • You may assume that the given expression is always valid.
  • Do not use the eval built-in library function.

代码:

class Solution {
public:
   int calculate(string s) {
	stack<char> ops;
	stack<int> nums;

	for (int i = 0; i < s.length(); i++) {
		if (s[i] == ' ')continue;
		if (isdigit(s[i])) {
			string temp = "";
			while (isdigit(s[i])) {
				temp.push_back(s[i]); i++;
			}
			i--;
			int tempint;
			stringstream ss;
			ss << temp;
			ss >> tempint;

			if (!ops.empty()&&ops.top() != '(') {
				char op = ops.top(); ops.pop();
				if (op == '+') {
					tempint += nums.top();
					nums.pop();
				}
				if (op == '-') {
					tempint = nums.top() - tempint;
					nums.pop();
				}
			}
			nums.push(tempint);
		}
		else if (s[i] == ')') {
			ops.pop();
			while (!ops.empty()&&ops.top()!='(') {
				char op = ops.top(); ops.pop();
				int a = nums.top(); nums.pop();
				int b = nums.top(); nums.pop();
				if (op == '-') {
					nums.push(b-a);
				}
				if (op == '+') {
					nums.push(a + b);
				}
			}
		}
		else ops.push(s[i]);
	}

	return nums.top();
}

};

思路:

使用两个栈来存储信息,一个栈是字符串栈,存储符号;一个栈是数字栈,存储运算的数。遍历字符串,遇到空格是continue,遇到数字的时候,读取他所在位置的后连起来的所有数字,组成一个数,判断opts栈顶的符号,如果符号不是(,那么取出符号和它nums栈顶的数,根据符号,将两个数根据该符号进行运算,运算结果再push到数字栈中;如果遇到的符号是')',那么pop出符号栈顶的那个符号(这个符号一定是‘(’),然后对符号栈和数栈一直进行符号运算并push进数栈的操作,知道碰到了‘(’符号或者符号栈为空。最后运算结束后,数栈中只剩下最后一个元素,那就是最后的运算结果,返回即可。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值