题目

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. 054 Spiral Matrix 旋转打印矩阵

    给出一个 m x n 的矩阵(m 行, n 列),请按照顺时针螺旋顺序返回元素.例如,给出以下矩阵:[ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ]]应该返回 [1,2, ...

  2. Codeforces Round #377 (Div. 2) E. Sockets

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

  3. Jenkins+Gitlab+Ansible自动化部署(二)

    接Jenkins+Gitlab+Ansbile自动化部署(一):https://www.cnblogs.com/zd520pyx1314/p/10210727.html Ansible的配置与部署 工 ...

  4. Ubuntu18.10设置静态IP、DNS、卸载无用软件

    设置静态IP root@xueji:~# vim /etc/network/interfaces # interfaces() ) and ifdown() auto lo iface lo inet ...

  5. HttpHelper使用记录

    重新载入页面以获取源代码 var item = new HttpItem() { URL = @"http://www.xxx.com/msg/basic/?a=sendmsg", ...

  6. 4. 把一幅彩色图像的R、G、B分量单独显示。

    #include <cv.h> #include <highgui.h> int main(void) { IplImage* oo = cvLoadImage(); IplI ...

  7. DialogHelper

    //require ScrollHelper.js function DialogHelper() { var _this = this; var doc = window.document; _th ...

  8. c#线程倒计时器源码

    using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threa ...

  9. android图片缩放平移

    <?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android=" ...

  10. jsp四大作用域之Session

    <%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding= ...