请写一个整数计算器,支持加减乘三种运算和括号。
数据范围:,保证计算结果始终在整型范围内
要求:空间复杂度: ,时间复杂度
# # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # 返回表达式的值 # @param s string字符串 待计算的表达式 # @return int整型 # # 最变态的题目了 class Solution: def solve(self , s ): # write code here while "(" in s: start = s.rfind("(") end = s[start:].find(")") + start sub_str = s[start: end + 1] temp = self.cal_no_brackets(sub_str[1:-1]) #print temp, s, start if temp < 0: if s[start-1] == "+": s = s.replace(sub_str, "0"+str(temp)) elif s[start-1] == "-": s = s.replace("-" + sub_str, "+" + str(-temp)) else: s = s.replace(sub_str, str(temp)) else: s = s.replace(sub_str, str(temp)) res = self.cal_no_brackets(s) return res def cal_no_brackets(self, string): array = self.split_string_to_array(string) if len(array) == 1: return int(array[0]) while "*" in array: index = array.index("*") number1 = int(array[index-1]) if array[index+1] == "-": number2 = -1*(int(array[index+2])) array = array[:index - 1] + [number1 * number2] + array[index + 3:] else: number2 = int(array[index + 1]) array = array[:index-1] + [number1*number2] + array[index+2:] while len(array) != 1: if array[0] == "-" and len(array) == 2: return -array[1] elif array[1] == "+": array = [int(array[0]) + int(array[2])] + array[3:] else: array = [int(array[0]) - int(array[2])] + array[3:] return array[0] def split_string_to_array(self, string): array = [] temp = "" for index in range(len(string)): if "0" <= string[index] <= "9": temp += string[index] else: if temp: array.append(temp) temp = "" array.append(string[index]) array.append(temp) return array