LeetCode(224) 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.
分析
简易计算器的实现。
需要两个栈,一个存放操作数,另一个存放操作符。
注意事项:
- 加减法没有交换律,每个操作数入栈时,都需查看操作符栈若有 + 或 - ,立即计算更新两个栈。
- 当遇到)时,将当前()内的表达式计算结果入栈,同时检查操作符栈若有 + 或 - ,立即计算更新两个栈。
AC代码
class Solution {
public:
int calculate(string s) {
if (s.empty())
return 0;
//求出所给表达式的长度
int len = s.length();
//操作符栈
stack<char> op_stack;
//操作数栈
stack<int> num_stack;
for (int i = 0; i < len; ++i)
{
//(1) 跳过空格
if (s[i] == ' ')
continue;
//(2) 操作符入栈
else if (s[i] == '(' || s[i] == '+' || s[i] == '-')
{
op_stack.push(s[i]);
continue;
}//elif
//(3) 右括号
else if (s[i] == ')')
{
while (op_stack.top() != '(')
{
//从数据栈弹出两个操作数
int num2 = num_stack.top();
num_stack.pop();
int num1 = num_stack.top();
num_stack.pop();
//从符号栈,弹出操作符
char op = op_stack.top();
op_stack.pop();
if (op == '+')
num_stack.push(num1 + num2);
else if (op == '-')
num_stack.push(num1 - num2);
}//while
//弹出左括号
op_stack.pop();
//此时查看操作数和操作符栈
while (!op_stack.empty() && op_stack.top() != '(')
{
//从数据栈弹出两个操作数
int num2 = num_stack.top();
num_stack.pop();
int num1 = num_stack.top();
num_stack.pop();
//从符号栈,弹出操作符
char op = op_stack.top();
op_stack.pop();
if (op == '+')
num_stack.push(num1 + num2);
else if (op == '-')
num_stack.push(num1 - num2);
}//while
}//elif
else{
int num = 0;
while (i < len && isDigit(s[i]))
{
num = num * 10 + (s[i] - '0');
i++;
}//while
//回退一个字符
--i;
num_stack.push(num);
//此时查看操作数和操作符栈
while (!op_stack.empty() && op_stack.top() != '(')
{
//从数据栈弹出两个操作数
int num2 = num_stack.top();
num_stack.pop();
int num1 = num_stack.top();
num_stack.pop();
//从符号栈,弹出操作符
char op = op_stack.top();
op_stack.pop();
if (op == '+')
num_stack.push(num1 + num2);
else if (op == '-')
num_stack.push(num1 - num2);
}//while
}
}//for
return num_stack.top();
}
bool isDigit(char c)
{
if (c >= '0' && c <= '9')
return true;
else
return false;
}
};
LeetCode(224) Basic Calculator的更多相关文章
- LeetCode(275)H-Index II
题目 Follow up for H-Index: What if the citations array is sorted in ascending order? Could you optimi ...
- LeetCode(220) Contains Duplicate III
题目 Given an array of integers, find out whether there are two distinct indices i and j in the array ...
- LeetCode(154) Find Minimum in Rotated Sorted Array II
题目 Follow up for "Find Minimum in Rotated Sorted Array": What if duplicates are allowed? W ...
- LeetCode(122) Best Time to Buy and Sell Stock II
题目 Say you have an array for which the ith element is the price of a given stock on day i. Design an ...
- LeetCode(116) Populating Next Right Pointers in Each Node
题目 Given a binary tree struct TreeLinkNode { TreeLinkNode *left; TreeLinkNode *right; TreeLinkNode * ...
- LeetCode(113) Path Sum II
题目 Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given ...
- LeetCode(107) Binary Tree Level Order Traversal II
题目 Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from l ...
- LeetCode(4)Median of Two Sorted Arrays
题目 There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the ...
- Leetcode(1)两数之和
Leetcode(1)两数之和 [题目表述]: 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标.你可以假设每种输入只会对应一 ...
随机推荐
- 线程池(1)ThreadPoolExecutor梳理
使用默认的 thread factory创建ThreadPoolExecutor实例 public ThreadPoolExecutor(int corePoolSize, int maximumPo ...
- Net Core -- 配置Kestrel端口
Net Core -- 配置Kestrel端口 Kestrel介绍 在Asp.Net Core中,我们的web application 其实是运行在Kestrel服务上,它是一个基于libuv开源的跨 ...
- Linux学习笔记——如何使用echo指令向文件写入内容
0.前言 本文总结如何使用echo命令向文件中写入内容,例如使用echo指令覆盖文件内容,使用echo指令向文件追加内容,使用echo指令往文件中追加制表符. echo向文件中输出内容 ...
- HATEOAS REST Service
用户通过点击页面的href的链接地址,而跳转到其他网页,实现浏览网页的过程了. -> 让调用REST的api就可以实现,类似于用户浏览网页的从一个页面跳转到另外一个页面的过程了 -> 而这 ...
- SyntaxError: Use of const in strict mode.
具体报错console c:\Users\Administrator\WebstormProjects\blogtest\node_modules\connect-mongo\src\index.js ...
- JS判断android ios系统 PC端和移动端
最近公司上线移动端,需要根据不同的系统跳转到不同的产品页面,百度后发现这一段代码很好用,不但可以判断当前是什么系统,还能知道当前浏览器是什么内核,移动端PC端都已测试无问题! var browser ...
- 超图supermap sdx数据库用sql实现空间查询
在此介绍用sql对超图的空间数据库(sdx)进行空间查询,优点如下: 1.超图推荐的方式是用iobject,此方法要引入iobject 2.超图另一个推荐的方式是用iserver的REST接口,但we ...
- UIWebView全解
是iOS内置的浏览器控件,可以浏览网页.打开文档等 能够加载html/htm.pdf.docx.txt等格式的文件 系统自带的Safari浏览器就是通过UIWebView实现的 MIME的英文全称是“ ...
- 大会聚焦 | 开源技术盛会LinuxCon首次来到中国,大咖齐聚关注业界动态
2017年6月19-20日,开源技术盛会LinuxCon + ContainerCon + CloudOpen(LC3)首次在中国举行.两天议程满满,包括 17 个主旨演讲.8 个分会场的 88 场技 ...
- 似水流年 ? Chrome调试大全
http://www.360doc.com/content/12/1107/20/7851074_246467307.shtml 作为一名前端开发者,打交道最多的可能是和浏览器.市面上各种浏览器多 ...