题目

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.

分析

简易计算器的实现。

需要两个栈,一个存放操作数,另一个存放操作符。

注意事项:

  1. 加减法没有交换律,每个操作数入栈时,都需查看操作符栈若有 + 或 - ,立即计算更新两个栈。
  2. 当遇到)时,将当前()内的表达式计算结果入栈,同时检查操作符栈若有 + 或 - ,立即计算更新两个栈。

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;
}
};

GitHub测试程序源码

LeetCode(224) Basic Calculator的更多相关文章

  1. LeetCode(275)H-Index II

    题目 Follow up for H-Index: What if the citations array is sorted in ascending order? Could you optimi ...

  2. LeetCode(220) Contains Duplicate III

    题目 Given an array of integers, find out whether there are two distinct indices i and j in the array ...

  3. LeetCode(154) Find Minimum in Rotated Sorted Array II

    题目 Follow up for "Find Minimum in Rotated Sorted Array": What if duplicates are allowed? W ...

  4. 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 ...

  5. LeetCode(116) Populating Next Right Pointers in Each Node

    题目 Given a binary tree struct TreeLinkNode { TreeLinkNode *left; TreeLinkNode *right; TreeLinkNode * ...

  6. 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 ...

  7. 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 ...

  8. 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 ...

  9. Leetcode(1)两数之和

    Leetcode(1)两数之和 [题目表述]: 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标.你可以假设每种输入只会对应一 ...

随机推荐

  1. ES6:string.raw浅析

    当前正学习ES6 ,遇到string.raw费心思,现将试验后的结果整理如下: 网上得来的试验: 语法 String.raw`templateStr`; String.raw(obj, ...subs ...

  2. (转)Nginx的https配置记录以及http强制跳转到https的方法梳理

    Nginx的https配置记录以及http强制跳转到https的方法梳理 原文:http://www.cnblogs.com/kevingrace/p/6187072.html 一.Nginx安装(略 ...

  3. JDBC连接中Class.forName("")到底干了什么?

    思考了一个问题,Class.forName("***");到底干了什么? 我们知道Class.forName( )静态方法的目的是为了动态加载类,但是一般来说,一个类forName ...

  4. 【翻译转载】【官方教程】Asp.Net MVC4入门指南(5):从控制器访问数据模型

    在本节中,您将创建一个新的MoviesController类,并在这个Controller类里编写代码来取得电影数据,并使用视图模板将数据展示在浏览器里. 在开始下一步前,先Build一下应用程序(生 ...

  5. 单机版mongodb

    1.下载安装包 wget http://fastdl.mongodb.org/linux/mongodb-linux-i686-1.8.2.tgz 下载完成后解压缩压缩包 tar zxf mongod ...

  6. 解决Chrome浏览器自动记录用户名和密码的黄色背景问题和该解决方法与tab切换至下一个input冲突的问题。

    哈哈哈,是不是标题很长呀,不逗你们了.其实这么长的标题主要就说了两件事: 第一件:解决Chrome浏览器自动记录用户名和密码的黄色背景问题. 第二件:输入完用户名后按下tab键切换至下一个输入密码in ...

  7. html的文档设置标记上(格式标记)4-5

    <html> <head> <title>第四课的标题及第五课的标题</title> <meta charset="utf-8" ...

  8. C++ error:Debug Assertion Failed.Expression:_BLOCK_TYPE_IS_VALID(phead->nBlock)

    Debug Assertion Failed.Expression:_BLOCK_TYPE_IS_VALID(phead->nBlockUse) 关于上面这个错误,我在上一篇文章中的程序遇到过了 ...

  9. 安装ubuntu出现BUG soft lockup的解决方法(16.04 14.04)

    对于16.04而言,当时用的是UtrISO 安装的,导致安装过程用会出现 “not a com32r image” 的错误,解决方法见上文的: boot: live 华硕Z9主板安装16.04以上系统 ...

  10. malloc/free函数

    一.malloc 函数原型:void *malloc(unsigned int size); 功       能:在内存的动态存储区中分配一个长度为size的连续空间. 返  回 值:指向所分配的连续 ...