[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-negativeintegers 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
evalbuilt-in library function.
这道题让我们实现一个基本的计算器来计算简单的算数表达式,而且题目限制了表达式中只有加减号,数字,括号和空格,没有乘除,那么就没啥计算的优先级之分了。于是这道题就变的没有那么复杂了。我们需要一个栈来辅助计算,用个变量sign来表示当前的符号,我们遍历给定的字符串s,如果遇到了数字,由于可能是个多位数,所以我们要用while循环把之后的数字都读进来,然后用sign*num来更新结果res;如果遇到了加号,则sign赋为1,如果遇到了符号,则赋为-1;如果遇到了左括号,则把当前结果res和符号sign压入栈,res重置为0,sign重置为1;如果遇到了右括号,结果res乘以栈顶的符号,栈顶元素出栈,结果res加上栈顶的数字,栈顶元素出栈。代码如下:
解法一:
class Solution {
public:
int calculate(string s) {
int res = , sign = , n = s.size();
stack<int> st;
for (int i = ; i < n; ++i) {
char c = s[i];
if (c >= '') {
int num = ;
while (i < n && s[i] >= '') {
num = * num + (s[i++] - '');
}
res += sign * num;
--i;
} else if (c == '+') {
sign = ;
} else if (c == '-') {
sign = -;
} else if (c == '(') {
st.push(res);
st.push(sign);
res = ;
sign = ;
} else if (c == ')') {
res *= st.top(); st.pop();
res += st.top(); st.pop();
}
}
return res;
}
};
下面这种方法和上面的基本一样,只不过对于数字的处理略微不同,上面的方法是连续读入数字,而这种方法是使用了一个变量来保存读入的num,所以在遇到其他字符的时候,都要用sign*num来更新结果res,参见代码如下:
解法二:
class Solution {
public:
int calculate(string s) {
int res = , num = , sign = , n = s.size();
stack<int> st;
for (int i = ; i < n; ++i) {
char c = s[i];
if (c >= '') {
num = * num + (c - '');
} else if (c == '+' || c == '-') {
res += sign * num;
num = ;
sign = (c == '+') ? : -;
} else if (c == '(') {
st.push(res);
st.push(sign);
res = ;
sign = ;
} else if (c == ')') {
res += sign * num;
num = ;
res *= st.top(); st.pop();
res += st.top(); st.pop();
}
}
res += sign * num;
return res;
}
};
在做了Basic Calculator III之后,再反过头来看这道题,发现递归处理括号的方法在这道题也同样适用,我们用一个变量cnt,遇到左括号自增1,遇到右括号自减1,当cnt为0的时候,说明括号正好完全匹配,这个trick在验证括号是否valid的时候经常使用到。然后我们就是根据左右括号的位置提取出中间的子字符串调用递归函数,返回值赋给num,参见代码如下:
解法三:
class Solution {
public:
int calculate(string s) {
int res = , num = , sign = , n = s.size();
for (int i = ; i < n; ++i) {
char c = s[i];
if (c >= '' && c <= '') {
num = * num + (c - '');
} else if (c == '(') {
int j = i, cnt = ;
for (; i < n; ++i) {
if (s[i] == '(') ++cnt;
if (s[i] == ')') --cnt;
if (cnt == ) break;
}
num = calculate(s.substr(j + , i - j - ));
}
if (c == '+' || c == '-' || i == n - ) {
res += sign * num;
num = ;
sign = (c == '+') ? : -;
}
}
return res;
}
};
类似题目:
Evaluate Reverse Polish Notation
Different Ways to Add Parentheses
参考资料:
https://leetcode.com/problems/basic-calculator/
https://leetcode.com/problems/basic-calculator/discuss/62361/Iterative-Java-solution-with-stack
https://leetcode.com/problems/basic-calculator/discuss/62362/JAVA-Easy-Version-To-Understand!!!!!
LeetCode All in One 题目讲解汇总(持续更新中...)
[LeetCode] Basic Calculator 基本计算器的更多相关文章
- [LeetCode] Basic Calculator III 基本计算器之三
Implement a basic calculator to evaluate a simple expression string. The expression string may conta ...
- [LeetCode] 224. Basic Calculator 基本计算器
Implement a basic calculator to evaluate a simple expression string. The expression string may conta ...
- [LeetCode] Basic Calculator IV 基本计算器之四
Given an expression such as expression = "e + 8 - a + 5" and an evaluation map such as {&q ...
- [LeetCode] Basic Calculator II 基本计算器之二
Implement a basic calculator to evaluate a simple expression string. The expression string contains ...
- LeetCode Basic Calculator II
原题链接在这里:https://leetcode.com/problems/basic-calculator-ii/ Implement a basic calculator to evaluate ...
- LeetCode Basic Calculator
原题链接在这里:https://leetcode.com/problems/basic-calculator/ Implement a basic calculator to evaluate a s ...
- Basic Calculator 基本计算器
2018-09-27 22:02:36 一.Basic Calculator II 问题描述: 问题求解: sign用来保存前一个符号,用num来记录数字,如果碰到一个符号或者到达结尾,则需要进行入栈 ...
- [LeetCode] Basic Calculator & Basic Calculator II
Basic Calculator Implement a basic calculator to evaluate a simple expression string. The expression ...
- LeetCode——Basic Calculator II
Description: Implement a basic calculator to evaluate a simple expression string. The expression str ...
随机推荐
- JAVA/GUI程序之记事本
自上半年JAVA课程结束后,再也没有看过JAVA了,最近不是很忙,又简单的看了看,本博客纯属记录学习过程,请大神们别笑,其中错误是难免的,毕竟是新手写的博客.下面就进入我们的正题吧,复习GUI时,就想 ...
- 浏览器自动刷新——基于Nodejs的Gulp LiveReload与VisualStudio完美结合。
本文版权桂博客园和作者吴双共同所有,转载和爬虫请注明原文地址 http://www.cnblogs.com/tdws/p/6016055.html 写在前面 大家好我是博客园的蜗牛,博客园的蜗牛就是我 ...
- asp.net MVC5 学习笔记(一)
Html.ActionLink("linkText","actionName") 该重载的第一个参数是该链接要显示的文字,第二个参数是对应的控制器的方法,默认控 ...
- 【转】Django Model field reference学习总结
Django Model field reference学习总结(一) 本文档包含所有字段选项(field options)的内部细节和Django已经提供的field types. Field 选项 ...
- java 开发业务逻辑的思考(1)- 通知短信发送
坚持每天写一个总结的博客,今天又是一个新的开始! 今天我要说的是一个关于发送短信通知发送的问题.具体的业务流程是这样的,现在需要对用户的一个提现的申请进行审核,审核的内部需要控制很多的业务, 1.检查 ...
- gearman 安装
yum install gperfyum install libevent-develyum install libuuid-develwget https://launchpad.net/gearm ...
- Javaweb项目框架搭建-准备篇
前言Java从大二开始学习到现在大四也有差不多两年了,但是由于之前一直在玩,没有认真学过,直到现在才开始重新学习.也是很凑巧,看到了黄勇老师的<架构探险>,于是便开始学习写Java Web ...
- 设计模式-策略模式(Strategy Model)
1.概述 在开发过程中常常会遇到类似问题,实现一个功能的时候往往有多种算法/方法(策略),我们可以根据环境的不同来使用不同的算法或策略来实现这一功能. 如在人物比较排序的实现中,我们有 ...
- 让IIS7.0.0.0支持 .iso .7z .torrent .apk等文件下载的设置方法
IIS默认支持哪些MIME类型呢,我们可以这样查看:打开IIS管理器(计算机--管理--服务和应用程序--Internet信息服务(IIS)管理器:或者Win+R,输入inetmgr,Enter),在 ...
- DevOps
DevOps DevOps(英文Development和Operations的组合)是一组过程.方法与系统的统称,用于促进开发(应用程序/软件工程).技术运营和质量保障(QA)部门之间的沟通.协作与整 ...