题解 | #表达式求值#

表达式求值

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

import java.util.Scanner;
import java.util.*;

/**
四则运算的解法
 */
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNextLine()) { 
            String str = in.nextLine();
            str.replace("{", "(");
            str.replace("[", "(");
            str.replace("}", ")");
            str.replace("]", ")");

            System.out.println(solve(str));
        }
    }

    private static int solve(String str) {
        Stack<Integer> stack = new Stack<>();
        int n = str.length();
        int num = 0;
        char sign = '+';
        
        for (int i = 0; i < n; i++) {
            char ch = str.charAt(i);
            if (Character.isDigit(ch)) {
                num = num * 10 + ch - '0';
            }

            if (ch == '(') {
                int count = 1;
                int j = i + 1;
                while (count > 0) {
                    if (str.charAt(j) == '(') {
                        count++;
                    }
                    if(str.charAt(j) == ')') {
                        count--;
                    }
                    j++;
                }
                num = solve(str.substring(i+1, j-1));
                i = j - 1;
            }

            if (!Character.isDigit(ch) || i == n - 1) {
                if (sign == '+') {
                    stack.push(num);
                }
                if (sign == '-') {
                    stack.push(-1 * num);
                }
                if (sign == '*') {
                    stack.push(stack.pop() * num);
                }
                if (sign == '/') {
                    stack.push(stack.pop() / num);
                }

                sign = ch;
                num = 0;
            }
        }

        int ans = 0;
        while (!stack.isEmpty()) {
            ans += stack.pop();
        }
        return ans;
    }
}

个人感觉四则运算这道题还是蛮难的,细节会比较多。

主要是用 栈 的思想来解决,但是在实现层面,需要对数值和操作符分别进行处理,然后默认操作符是 + 这个思想很棒;另外的亮点就是 对( 的解决,主要是用了递归。

全部评论

相关推荐

迷茫的大四🐶:自信一点,我认为你可以拿到50k,低于50k完全配不上你的能力,兄弟,不要被他们骗了,你可以的
点赞 评论 收藏
分享
求面试求offer啊啊啊啊:要求太多的没必要理
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务