题目

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. centos下svnadmin的部署过程

    1.    安装SVN #yum –y install subversion 2.    安装openjdk #yum –y list java* #yum –y install java-1.8.0 ...

  2. 050 Pow(x, n)

    实现 pow(x, n).示例 1:输入: 2.00000, 10输出: 1024.00000示例 2:输入: 2.10000, 3输出: 9.26100详见:https://leetcode.com ...

  3. tomcat7 fail to start inside Ubuntu Docker container

    The tomcat startup script needs some special privileges. Concrete it needs to check all running proc ...

  4. 一文读懂DDD

    何为DDD DDD不是架构设计方法,不能把每个设计细节具象化,DDD是一套体系,决定了其开放性,体系中可以用任何一种方法来解决这些问题,但是如果一些关键问题没有具体方案落地,可能让团队无所适从. 有的 ...

  5. 洪水 Pow

    Description AKD市处在一个四面环山的谷地里.最近一场大暴雨引发了洪水,AKD市全被水淹没了.Blue Mary,AKD市的市长,召集了他的所有顾问(包括你)参加一个紧急会议.经过细致的商 ...

  6. E. Karen and Supermarket

    E. Karen and Supermarket time limit per test 2 seconds memory limit per test 512 megabytes input sta ...

  7. 基于JAVA的设计模式之适配器模式

    适配器模式概念 适配器模式把一个类的接口变换成客户端所期待的另一个接口,从而使原本因接口不匹配而无法在一起工作的两个类能够在一起工作.比如我们突然就想看电影了,但是这个电影是AVI格式的,目前我们开发 ...

  8. 剑指tomcat之应用管理

    tomcat服务启动之后,有tomcat自身提供的应用管理(App Manage)页面,默认的地址就是服务的IP地址+端口号(IP:port):页面如下所示 点击上图的按钮便可进入应用管理页面,需要账 ...

  9. jquery.restrictFieldLength.js

    1.参考资料 http://www.cnblogs.com/aarond/archive/2013/08/02/3234042.html 2.使用举例 //字符控制 $(function () { $ ...

  10. 检查EXE、DLL、SYS等文件是32位还是64位的

    非.NET文件用:dumpbin.exe /headers file.exe(C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\bin) . ...