题解 | #表达式求值#

表达式求值

https://www.nowcoder.com/practice/9566499a2e1546c0a257e885dfdbf30d

import java.util.*;

// 整体思路把所有复杂项转成+-算法,并把每一个带符号的数字放到栈内
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String str = in.nextLine();
        System.out.print(run(str));
    }

    public static int run(String str) {
        Stack<Integer> stack = new Stack<>();

        char lastSign = '+';
        int lastNum = 0;
        for (int i = 0; i < str.length(); i++) {
            // 遇到数字,组合数字
            if (Character.isDigit(str.charAt(i))) {
                StringBuffer sb = new StringBuffer();
                int j = i;
                while (j < str.length() && Character.isDigit(str.charAt(j))) {
                    sb.append(str.charAt(j));
                    j++;
                }
                i = j == str.length() ? --j : j;
                lastNum = Integer.valueOf(sb.toString());
            }
            // 遇到括号,重新压入新栈计算括号内
            if (str.charAt(i) == '(') {
                int j = i + 1;
                int count = 1;
                while (count != 0) {
                    if (str.charAt(j) == '(') {
                        count++;
                    }
                    if (str.charAt(j) == ')') {
                        count--;
                    }
                    ++j;
                }
                lastNum = run(str.substring(i + 1, j - 1));
                i = j - 1;
            }
            // 遇到+-*/符号,计算环节
            if (!Character.isDigit(str.charAt(i)) || i + 1 == str.length()) {
                if (lastSign == '+') {
                    stack.push(lastNum);
                }
                if (lastSign == '-') {
                    stack.push(-1 * lastNum);
                }
                if (lastSign == '*') {
                    stack.push(stack.pop() * lastNum);
                }
                if (lastSign == '/') {
                    stack.push(stack.pop() / lastNum);
                }
                lastSign = str.charAt(i);
            }
        }
        int sum = 0;
        while (!stack.isEmpty()) {
            sum += stack.pop();
        }
        return sum;
    }
}

重新写第二次,还是边界很麻烦,以及思路:

栈,遇到数字取出,遇到括号递归,遇到符号则把带符号数字存到栈里,最后循环取出栈数据相加

全部评论

相关推荐

06-01 21:50
已编辑
天津理工大学 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务