(LeetCode 224)基本计算器

题目描述

栈对于中缀表达式求值的应用:中缀——后缀——求值
中缀转后缀时可以直接返回两个队列?(返回字符串太慢了。。。)

代码如下(124ms/10.8MB):

string translate(string s) {
	string result = "", temp = "";
	for (int i = 0; i < s.size(); ++i) {
		if (s[i] - '0' < 10 && s[i] - '0' >= 0) temp += s[i];
		else {
			if (temp != "") {
				result += (temp + ' ');
				temp = "";
			}
			if (s[i] == '(') punc.push(s[i]);
			else if (s[i] == ')'||s[i] == '+' || s[i] == '-') {
				while (!punc.empty()) {
					if (punc.top() == '(') break;
					result += punc.top();
					punc.pop();
				}
				if(s[i] == ')') punc.pop();
				else punc.push(s[i]);
			}
			else if (s[i] == '*' || s[i] == '/') {
				while (!punc.empty()) {
					if (punc.top() != '*' || punc.top() != '/') {
						punc.push(s[i]);
						break;
					}
					result += punc.top();
					punc.pop();
				}
			}
		}
	}
	if (temp != "") result += (temp + ' ');
	while (!punc.empty()) {
		result += punc.top();
		punc.pop();
	}
	return result;
}

int calculate(string s) {
	string sl = translate(s);
	string temp = "";
	for (int i = 0; i < sl.size(); ++i) {
		if (sl[i] - '0' >= 0 && sl[i] - '0' < 10) temp += sl[i];
		else if (sl[i] == ' ') {
			num.push(stoi(temp));
			temp = "";
		}
		else {
			int n1 = num.top();
			num.pop();
			int n2 = num.top();
			num.pop();
			if (sl[i] == '+') num.push(n2 + n1);
			else if (sl[i] == '-') num.push(n2 - n1);
			else if (sl[i] == '*') num.push(n2 * n1);
			else if (sl[i] == '/') num.push(n2 / n1);
		}
	}
	return num.top();
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值