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,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标.你可以假设每种输入只会对应一 ...
随机推荐
- spoolight on oracle 配置
spoolight seting 1ORACLE_HOME=D:\oracle\product\11.2.0\client_1set SQLPATH=D:\oracle\product\11.2.0\ ...
- 使用cp命令拷贝目录下指定文件外的其他文件
shopt -s extglob cp test/!(abc*) test2/ cp test目录下除了以abc开头的其他文件 如果是除去多个文件的话使用 !(a|b) ; 注意不要多加空 ...
- Spring Boot 集成 PageHelper
配置一:在 [pom.xml] 文件中引入依赖 <!-- mybatis的分页插件 --> <dependency> <groupId>com.github.pag ...
- JAVA---spring-boot入门(图文教程)
Spring Boot可以轻松创建独立的,生产级的基于Spring的应用程序,他的特征: 1.创建独立的Spring应用程序 2.直接嵌入Tomcat,Jetty或Undertow(无需部 ...
- 【Unity3D】点击交互——简单工厂
实现一个很简单的点击小游戏,学习交互相关的内容,在不实时创建销毁的情况下,使用简单工厂创建.管理.回收.复用标记. 游戏概述:点击出现标记,两秒内自动消失 游戏展示: 1.1实现点击效果. 1.1.1 ...
- 【javascript类库】zepto和jquery的md5加密插件
[javascript类库]zepto和jquery的md5加密插件 相信很多人对jQuery并不陌生,这款封装良好的插件被很多开发者使用. zepto可以说是jQuery在移动端的替代产品,它比jQ ...
- 扒一扒IT大佬高考:马云数学1分考北大 李彦宏是状元
http://news.cnblogs.com/n/522622/ 高考今天正式拉开序幕,而像李彦宏.马云等 IT 大佬之前也都参加过高考,他们成绩又都是怎样的呢? 马化腾:放弃天文梦选择计算机 20 ...
- 简单案列完美搞定Mvc设计模式
一个小列子搞定Mvc模式,包括数据库以及如何提高用户体验度 1.首先来web.xml配置servlet的访问路径: <?xml version="1.0" encoding= ...
- CF 55D Beautiful numbers (数位DP)
题意: 如果一个正整数能被其所有位上的数字整除,则称其为Beautiful number,问区间[L,R]共有多少个Beautiful number?(1<=L<=R<=9*1018 ...
- itextsharp-5.2.1-修正无法签名大文件问题
PDF文件格式几乎是所有开发平台或者业务系统都热爱的一种文档格式. 目前有很多优秀的开源PDF组件和类库.主要平时是使用.NET和Java开发,所以比较偏好使用iText,当然,它本身就很强大.iTe ...