题解 | #表达式求值#
表达式求值
https://www.nowcoder.com/practice/c215ba61c8b1443b996351df929dc4d4
# # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # # 返回表达式的值 # @param s string字符串 待计算的表达式 # @return int整型 # class Solution: def solve(self , s: str) -> int: # write code here if '(' not in s: start = s.find('*') if start == -1: s = s.replace('+-', '-') s = s.replace('--', '+') start = s.find('+') if start == -1: start = s.rfind('-') if start == -1 or start == 0: if s == '': return 0 else: return int(s) else: return self.solve(s[:start]) - self.solve(s[start + 1:]) else: return self.solve(s[:start]) + self.solve(s[start + 1:]) else: left, right = s[:start], s[start + 1:] num1 = '' while left != '' and left[-1].isdecimal(): num1 = left[-1] + num1 left = left[:-1] num2 = '' while (right != '' and right[0].isdecimal()) or num2 == '': num2 = num2 + right[0] right = right[1:] return self.solve(left + str(int(num1) * int(num2)) + right) else: start = s.find('(') parse = 0 for end in range(len(s)): if s[end] == '(': parse += 1 elif s[end] == ')': parse -= 1 if parse == 0: break sub_str = s[start + 1: end] val = self.solve(sub_str) if val == 6: print(val) new_str = s[:start] + str(val) + s[end + 1:] return self.solve(new_str)