1. 题目
www.nowcoder.com/practice/c2…

2. 题目解析
1. 写一个支持 + - * 运算 ‘*’ 优先处理
2. 只有()符号
3. 考点: 栈 + 递归
- step 1:使用栈辅助处理优先级,默认符号为加号。
- step 2:遍历字符串,遇到数字,则将连续的数字字符部分转化为int型数字。
- step 3:遇到左括号,则将括号后的部分送入递归,处理子问题;遇到右括号代表已经到了这个子问题的结尾,结束继续遍历字符串,将子问题的加法部分相加为一个数字,返回。
- step 4:当遇到符号的时候如果是+,得到的数字正常入栈,如果是-,则将其相反数入栈,如果是*,则将栈中内容弹出与后一个元素相乘再入栈。
- step 5:最后将栈中剩余的所有元素,进行一次全部相加。
4. 核心代码
b = '(2*(3-4))*5'
print(eval(b))
def test(s: str):
stack = []
ind = 0
num = 0
sign = '+'
while ind < len(s):
if s[ind] == '(':
end = ind + 1
lens = 1
while lens > 0:
if s[end] == '(':
lens += 1
elif s[end] == ')':
lens -= 1
end += 1
num = test(s[ind + 1: end - 1])
ind = end - 1
continue
if '0' <= s[ind] <= '9':
num = num * 10 + int(s[ind])
if not '0' <= s[ind] <= '9' or ind == len(s) - 1:
if sign == '+':
stack.append(num)
elif sign == '-':
stack.append(-num)
elif sign == '*':
stack.append(stack.pop() * num)
num = 0
sign = s[ind]
ind += 1
return sum(stack)
if __name__ == '__main__':
print(test('-3+2*3*4-1'))