leetcode

it2022-05-05  72

解题思路:

按照两个栈的思路去导入数字和数学操作,然后根据先乘除后加减的法则,找到第一个操作数和第二操作数即可。

具体代码如下:

class Solution: def calculate(self, s: str) -> int: string = '' for char in s: if char != ' ': string += char nums = [] operations = [] ops = ['+', '-', '*', '/'] tmp = 0 for char in string: if char not in ops: tmp = tmp * 10 + int(char) else: nums.append(tmp) tmp = 0 operations.append(char) nums.append(tmp) first = nums[0] second = '#' flag = '#' for i in range(1, len(nums)): if second == '#' and operations[i - 1] == '*': first = first * nums[i] if second == '#' and operations[i - 1] == '/': first = first // nums[i] if second != '#' and operations[i - 1] == '*': second = second * nums[i] if second != '#' and operations[i - 1] == '/': second = second // nums[i] if second != '#' and operations[i - 1] == '+': if flag == '+': first += second second = '#' flag = '+' if flag == '-': first -= second second = '#' flag = '+' if second != '#' and operations[i - 1] == '-': if flag == '+': first += second second = '#' flag = '-' elif flag == '-': first -= second second = '#' flag = '-' if second == '#' and operations[i - 1] == '+': second = nums[i] flag = '+' if second == '#' and operations[i - 1] == '-': second = nums[i] flag = '-' if second == '#': return first else: if flag == '+': return first + second else: return first - second

最新回复(0)