题解 | #表达式求值#

表达式求值

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;
    }
}

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

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

全部评论

相关推荐

fRank1e:吓得我不敢去外包了,但是目前也只有外包这一个实习,我还要继续去吗
点赞 评论 收藏
分享
程序员牛肉:主要是因为小厂的资金本来就很吃紧,所以更喜欢有实习经历的同学。来了就能上手。 而大厂因为钱多,实习生一天三四百的就不算事。所以愿意培养你,在面试的时候也就不在乎你有没有实习(除非是同级别大厂的实习。) 按照你的简历来看,同质化太严重了。项目也很烂大街。 要么换项目,要么考研。 你现在选择工作的话,前景不是很好了。
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-01 12:22
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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