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,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标.你可以假设每种输入只会对应一 ...
随机推荐
- Qt5.7中使用MySQL Driver(需要把libmysql.dll文件拷贝到Qt的bin目录中。或者自己编译的时候,链接静态库)
Qt5.7中使用MySQL Driver 1.使用环境 Qt5.7的安装安装就已经带了MySQL Driver,只需要在安装的时候选择一下即可.如果没有安装,可以采取自己编译的方式.在Qt的源码包的q ...
- Windows3
windows安装后的配置 没有网络适配器, 将USB中的驱动精灵的安装程序安装在win上, 启动精灵, 提示无法连接到网络, 使用Android类型的手机中的QQ浏览器扫码下载 win会有一些开机自 ...
- kie-api 组件介绍
KieServices:kie整体的入口,可以用来创建Container,resource,fileSystem等 KieContainer: KieContainer就是一个KieBase的容器,可 ...
- 基于Java实现的快速排序
简述 快速排序是一种排序执行效率很高的排序算法,它利用分治法来对待排序序列进行分治排序,它的思想主要是通过一趟排序将待排记录分隔成独立的两部分,其中的一部分比关键字小,后面一部分比关键字大,然后再对这 ...
- 缓存List并写入文件持久化
LIfe is half spent before we know what is it. 缓存List并写入文件持久化 需要缓存一个List集合,比如缓存一个输入框中用户之前输入过的内容,下次当用户 ...
- css常用操作
对齐操作 1.使用margin属性进行水平对齐 margin-left:auto; margin-right:auto; 2.使用position属性进行左右对齐 3.使用fl ...
- 9、数值的整数次方------------>剑指offer系列
数值的整数次方 给定一个double类型的浮点数base和int类型的整数exponent.求base的exponent次方. 思路 这道题逻辑上很简单,但很容易出错 关键是要考虑全面,考虑到所有情况 ...
- Chrome Java插件过期
企业应用软件中,基本都是基于某个版本的JDK进行开发的,更新跟不上Oracle更新的步伐,Chrome浏览器自动默认关闭了过期插件导致用Chrome无法打开应用软件. 解决办法如下:
- IDEA的第一个JavaEE项目&集成Tomcat、Jrebel、Git插件
创建第一个JavaEE项目 Next之后选择项目存储位置之后点击Finish即可. 新建的项目需要新建两个文件夹classes和lib 集成Tomcat Tomcat自行到官网下载 JRebel集成 ...
- Python3+Selenium3+webdriver学习笔记7(选择多链接的结果、iframe、下拉框)
#!/usr/bin/env python# -*- coding:utf-8 -*- from selenium import webdriverfrom selenium.webdriver.co ...