题目如下:

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. spring ehcache 缓存框架

    一.简介 Ehcache是一个用Java实现的使用简单,高速,实现线程安全的缓存管理类库,ehcache提供了用内存,磁盘文件存储,以及分布式存储方式等多种灵活的cache管理方案.同时ehcache ...

  2. 哈希表 HashTable(又名散列表)

    简介 其实通过标题上哈希表的英文名HashTable,我们就可以看出这是一个组合的数据结构Hash+Table. Hash是什么?它是一个函数,作用可以通过一个公式来表示: index = HashF ...

  3. 基于LVM(逻辑卷管理)的快照原理

    一.为甚么不管多大的逻辑卷进行备份,快照都会在几秒之内完成? 快照在拍摄的一瞬间,系统会记录那个时间点逻辑卷的状态.数据等,此时拍下的快照相当于一张白纸.如图所示 快照做好后,随着时间的推移,源卷里的 ...

  4. 爬虫七之分析Ajax请求并爬取今日头条

    爬取今日头条图片 这里只讨论出现的一些问题,代码在最下面github链接里. 首先,今日头条取消了"图集"这一选项,因此对于爬虫来说效率降低了很多: 在所有代码都完成后,也许是爬取 ...

  5. 3、APK file does not exist on disk

    参考:https://blog.csdn.net/ouyang_peng/article/details/51243441 亲测可以解决

  6. laravel修改用户模块的密码验证

    做项目的时候,用户认证几乎是必不可少的,如果我们的项目由于一些原因不得不使用 users 之外的用户表进行认证,那么就需要多做一点工作来完成这个功能. 现在假设我们只需要修改登录用户的表,表名和表结构 ...

  7. MQ的用途与对比

    RabbitMQ系列第一课:RabbitMQ安装 RabbitMQ系列第二课:RabbitMQ的原理介绍 RabbitMQ系列第三课:MQ用途与产品对比 一.MQ的用途:解耦和流量肖锋  二.常用MQ ...

  8. Android热修复、插件化、组件化

    模块化:项目按照独立的模块进行划分 组件化:将项目按照单一的组件来进行划分结构 项目组件化的重要环节在于,将项目按照模块来进行拆分,拆分成一个个业务module和其他支撑module(lib),各个业 ...

  9. php获取某经纬度附近地点位置

    最近在做小程序中 其中一个需求就是要到找出某个经纬度地点附近的位置 本质最终的目的就是确定以某个确定的经纬度地点,以某半径画圆形确定的4个点对应的经纬度 /** * [returnSquarePoin ...

  10. QItemDelegate edit某个控件后把数据写回model

    QWidget *TrackDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const ...