題目
波蘭表達(dá)式
遍歷tokens楞陷,如果遇到三個(gè)符號(hào)符合波特蘭式,則計(jì)算并修改tokens摹菠。最后的tokens只有一個(gè)元素盒卸,即最后的結(jié)果。
class Solution:
def evalRPN(self, tokens) -> int:
tlen = len(tokens)
lookuptb = set(['+','-','*','/'])
i = 0
while i+2<tlen:
if tokens[i] not in lookuptb and tokens[i+1] not in lookuptb and tokens[i+2] in lookuptb:
num1 = int(tokens[i])
num2 = int(tokens[i+1])
if tokens[i+2]=='+':
newtoken = num1 + num2
elif tokens[i+2]=='-':
newtoken = num1 - num2
elif tokens[i+2]=='*':
newtoken = num1 * num2
else:
newtoken = int(num1 / num2)
tokens.pop(i+2)
tokens.pop(i+1)
tokens.pop(i)
tokens.insert(i,str(newtoken))
tlen -= 2
if i>0:
i -= 1
else:
i += 1
return int(tokens[0])
用棧的方法也可以次氨,遍歷tokens世落,遇到數(shù)字進(jìn)棧,遇到符號(hào)則取出棧頂兩個(gè)元素進(jìn)行運(yùn)算后再次入棧。