题目

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. 043 Multiply Strings 字符串相乘

    给定两个以字符串表示的非负整数 num1 和 num2,返回 num1 和 num2 的乘积.注意:    num1 和 num2 的长度均小于110.    num1 和 num2 均只包含数字 0 ...

  2. Aspose.word组件介绍

    阅读目录 1.基本介绍 2.文档对象模型概述        本博客所有文章分类的总目录:http://www.cnblogs.com/asxinyu/p/4288836.html 本博客其他.NET开 ...

  3. P4876 近似排列计数50

    时间限制:1s 内存限制:256MB [问题描述] 对于一个1-n的排列,如果满足第i个数|ai-i|<=k,则称该排列为K-近似排列. 现在排列的若干位置已经确定,你需要计算剩下的数有多少种排 ...

  4. return void ajax

    public class UserInfo { private String name; private Integer age; public String getName() { return n ...

  5. 【Design Patterns】监听器模式

    监听器模式 监听器模式其实是观察者模式中的一种,两者都有关于回调的设计. 与观察者模式不同的是,观察者模式中存在的角色为观察者(Observer)和被观察者(Observable) 而监听器模式中存在 ...

  6. Date 对象 时间格式注意事项

    Date 对象,是操作日期和时间的对象. Date 为内置的构造函数, 通过 new Date () 来获取当前本地日期与时间 const time = new Date console.log(ti ...

  7. HBuilder 做移动端app流程

    1.新建一个移动项目 2.编写代码 3.发行-发行为原生安装包,配置参数 选择icon 和引导页

  8. 带你零基础入门redis【二】

    本篇文章介绍redis如何设置开机自启动以及如何在java中应用 一.设置redis开机自启 1.修改redis配置 [root@VM_6_102_centos ~]# vim /usr/local/ ...

  9. 关于IT公司招聘的一个思考

    作者:朱金灿 来源:http://blog.csdn.net/clever101 21世纪什么最贵?人才!相信这是很多IT公司管理者的深刻感悟.对于IT公司而言,找到合适的人才往往不能单靠人事部门,一 ...

  10. 【虚拟机-网络IP】虚拟机配置静态 IP 以后无法连接的解决办法

    问题描述 将虚拟机内部 IP 地址从动态获取改成静态 IP 以后,远程连接失败. 问题分析 Azure 虚拟机的内部 IP 默认为动态分配, 由 DHCP 服务自动分配, 在虚拟机的生命周期内, 该 ...