题目如下:

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 .

The expression string contains only non-negative integers, +, -, *, / operators , open ( and closing parentheses ) and empty spaces . The integer division should truncate toward zero.

You may assume that the given expression is always valid. All intermediate results will be in the range of [-2147483648, 2147483647].

Some examples:

"1 + 1" = 2
" 6-4 / 2 " = 4
"2*(5+5*2)/3+(6/2+8)" = 21
"(2+6* 3+5- (3*14/7+2)*5)+3"=-12 Note: Do not use the eval built-in library function.

解题思路:算法上没有什么技术难度,无非就是要考虑各种情况。我的方法是用两个栈分别保存运算符号和非运算符号(包括数字和括号)。遇到右括号后,往前找左括号,遇到乘号或者除号,直接计算出结果。

代码如下:(写的很乱,也没心情优化了)

class Solution(object):
operator = []
num = []
def calcMandD(self,v):
if len(self.operator) == 0 or len(self.num) == 0:
return False
if (self.operator[-1] == '*' or self.operator[-1] == '/') and (self.num[-1] != '(' and self.num[-1] != ')'):
if self.operator[-1] == '*' :
tmp = int(self.num[-1]) * int(v)
self.num[-1] = str(tmp)
else:
tmp = int(self.num[-1]) / int(v)
self.num[-1] = str(tmp)
del self.operator[-1]
return True
return False
def calcParentheses(self):
t1 = self.num[-1]
del self.num[-1] tn = []
to = [] tn.append(t1) while self.num[-1] != '(':
t2 = self.num[-1] to.insert(0, self.operator[-1])
tn.insert(0, t2)
del self.operator[-1]
del self.num[-1]
del self.num[-1] #del ( t1 = tn[0]
del tn[0]
while len(tn) > 0:
t2 = tn[0]
if to[0] == '+':
t1 = int(t1) + int(t2)
elif to[0] == '-':
t1 = int(t1) - int(t2)
del to[0]
del tn[0]
return str(t1)
#self.num.append(str(t1))
def calcAandM(self):
t1 = self.num[0]
del self.num[0]
while len(self.num) > 0:
t2 = self.num[0]
if self.operator[0] == '+':
t1 = int(t1) + int(t2)
elif self.operator[0] == '-':
t1 = int(t1) - int(t2)
del self.operator[0]
del self.num[0]
return int(t1) def calculate2(self, s):
n = ''
for i in s:
if i == ' ':
continue
if i == '+' or i == '-' or i == '*' or i == '/':
if n != '':
if self.calcMandD(n) == False:
self.num.append(n)
n = ''
self.operator.append(i)
continue
if i == '(':
if n != '':
self.num.append(n)
n = ''
self.num.append(i)
continue
if i == ')':
if n != '':
if self.calcMandD(n) == False:
self.num.append(n)
n = ''
ret = self.calcParentheses()
while len(self.operator) >0 and (self.operator[-1] == '*' or self.operator[-1] == '/') and (self.num[-1] != '(' and self.num[-1] != ')'):
if self.operator[-1] == '*':
#print self.num
#print self.operator
ret = int(self.num[-1]) * int(ret)
else:
ret = int(self.num[-1])/int(ret)
del self.operator[-1]
del self.num[-1]
self.num.append(ret) continue
if i>='' and i <= '':
n += i
if n!='':
if self.calcMandD(n) == False:
self.num.append(n) def calculate(self, s):
"""
:type s: str
:rtype: int
"""
self.operator = []
self.num = []
self.calculate2(s)
#print (self.operator)
#print (self.num)
return self.calcAandM()

【leetcode】Basic Calculator III的更多相关文章

  1. [LeetCode] 772. Basic Calculator III 基本计算器之三

    Implement a basic calculator to evaluate a simple expression string. The expression string may conta ...

  2. leetcode 772.Basic Calculator III

    这道题就可以结合Basic Calculator中的两种做法了,分别是括号运算和四则运算的,则使用stack作为保持的结果,而使用递归来处理括号内的值的. class Solution { publi ...

  3. 【LeetCode】Broken Calculator(坏了的计算器)

    这道题是LeetCode里的第991道题. 题目描述: 在显示着数字的坏计算器上,我们可以执行以下两种操作: 双倍(Double):将显示屏上的数字乘 2: 递减(Decrement):将显示屏上的数 ...

  4. 【LeetCode】House Robber III(337)

    1. Description The thief has found himself a new place for his thievery again. There is only one ent ...

  5. 【leetcode】Combination Sum III(middle)

    Find all possible combinations of k numbers that add up to a number n, given that only numbers from ...

  6. 【LeetCode】字符串 string(共112题)

    [3]Longest Substring Without Repeating Characters (2019年1月22日,复习) [5]Longest Palindromic Substring ( ...

  7. 【LeetCode】栈 stack(共40题)

    [20]Valid Parentheses (2018年11月28日,复习, ko) 给了一个字符串判断是不是合法的括号配对. 题解:直接stack class Solution { public: ...

  8. 【LeetCode】数学(共106题)

    [2]Add Two Numbers (2018年12月23日,review) 链表的高精度加法. 题解:链表专题:https://www.cnblogs.com/zhangwanying/p/979 ...

  9. 【LeetCode】哈希表 hash_table(共88题)

    [1]Two Sum (2018年11月9日,k-sum专题,算法群衍生题) 给了一个数组 nums, 和一个 target 数字,要求返回一个下标的 pair, 使得这两个元素相加等于 target ...

随机推荐

  1. 【FICO系列】SAP FICO折旧记账时出现错误:没有找到与所做选择一致的数据

    公众号:SAP Technical 本文作者:matinal 原文出处:http://www.cnblogs.com/SAPmatinal/ 原文链接:[FICO系列]SAP FICO折旧记账时出现错 ...

  2. stringbuffer.tostring引发的 Java heap space

    今天在测试“生成报告“功能时,出现了这个问题,java抛出java.lang.OutOfMemoryError: Java heap space: 由于开发使用的tomcat是统一配置的,而且其他地方 ...

  3. 主机加固之windows2003

    这篇与上一篇的win7主机加固内容大体类似,部分有些不同.这篇也可以用来尝试加固windows XP. 1. 配置管理 1.1用户策略 注意:在对Windows系统加固之前先新建一个临时的系统管理员账 ...

  4. tarjan缩点相关知识及代码

    emmm原谅我确实是找不到不用缩点的tarjan题才会想到自学一下缩点这个东西的.. 题目没有,只能自己出数据并手动模拟... 首先看一张图(懒得画,还是看输入数据吧,劳烦自行画图..) 7 9(n个 ...

  5. java中抽象类、接口及区别

    转自:http://www.cnblogs.com/dolphin0520/p/3811437.html 一.抽象类 在了解抽象类之前,先来了解一下抽象方法.抽象方法是一种特殊的方法:它只有声明,而没 ...

  6. Spark架构角色及基本运行流程

    1. 集群角色 Application:基于spark的用户程序,包含了一个Driver program 和集群中多个Executor Driver Program:运行application的mai ...

  7. Spring(十)--Advisor顾问

    Spring之Advisor顾问 1. 创建新的xml文件  advisor.xml <!--01. 配置目标对象 实际肯定是配置UserServiceImpl--> <bean i ...

  8. 理解ES6的模块导入与导出

    export export后必须跟语句, 何为语句, 如声明, for, if 等都是语句, export 不能导出匿名函数, 也不能导出某个已经声明的变量, 如: export const bar ...

  9. Java最新学习线路(基础,源码,项目,实战)

    如需获取以下学习资源请关注公众号:Java编程指南 我们为自学者编程的或初学java的小伙伴们准备了一整套完整的学习资源和文章,还有我自己在自学路上的一些总结和学习线路,希望能帮到小伙伴们,如果有什么 ...

  10. 【五一qbxt】test2

    又犯了一些迷之错误??要不然yy鼠标就是我的了 1.Superman: 小姐姐的题解:直接用set模拟即可emmmm 里面有很多指针啊,乱七八糟的,不会qwq,先看看我的大模拟吧: #include& ...