题目

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. Codeforces Round #377 (Div. 2) E. Sockets

    http://codeforces.com/contest/732/problem/E 题目说得很清楚,每个电脑去插一个插座,然后要刚好的,电脑的power和sockets的值相同才行. 如果不同,还 ...

  2. 《深入理解java虚拟机》笔记(3)实战:OutOfMemoryError异常

    一.Java堆溢出 测试代码: /** * <p>Java堆异常测试</p> * <code>VM Args: -Xms20m -Xmx20m -XX:+HeapD ...

  3. 如何在windows下是用mysqldumpslow命令

    1. 再一次点击mysql安装文件(默认是没安装mysqldumpslow这些脚本的),如图: 点击next如下图 点击Developer Components 旁边的选择this feature , ...

  4. windows黑窗口关于java程序的常用命令

    1.启动java程序 我要运行:E:\code\nhtask下的ElectricEye-0.0.1-SNAPSHOT.jar程序 #切换到程序目录cd E:\code\nhtaskE: java -j ...

  5. 深入JVM内核---原理,诊断与优化

    JVM的概念 JAM是Java Virtual Machine的简称.意为Java虚拟机 虚拟机 指通过软件模拟的具有完整硬件系统功能的,运行在一种完整隔离环境中的完整计算机系统 有哪些虚拟机 - V ...

  6. 用Node+wechaty写一个爬虫脚本每天定时给女(男)朋友发微信暖心话

    wechatBot 微信每日说,每日自动发送微信消息给你心爱的人 项目介绍 灵感来源 在掘金看到了一篇<用Node + EJS写一个爬虫脚本每天定时女朋友发一封暖心邮件>后, 在评论区偶然 ...

  7. (原创)linux下Microsoft/cpprestsdk支持https(server)

    原创,转载请标明源地址 之前看网上一堆的资料说Microsoft/cpprestsdk不支持https或者说只支持window下的https,差点就被误导了,没办法,只好自己去翻了下源代码 先说明下l ...

  8. python读xml文件

    # -*- coding:utf-8 -*- import jsonimport requestsimport os curpath=os.path.dirname(os.path.realpath( ...

  9. JavaScript_3_输出

    1. JavaScript通常用于操作HTML元素,可以使用getElementById(id)方法. JavaScript由Web浏览器来执行. 2. document.write()仅仅向文档输出 ...

  10. 【Python图像特征的音乐序列生成】使用Python生成简单的MIDI文件

    这个全新的Python音乐创作系列,将会不定期更新.写作这个系列的初衷,是为了做一个项目<基于图像特征的音乐序列生成模型>,实时地提取照片特征,进行神经网络处理,生成一段音乐. 千里之行, ...