数据结构:使用Stack完成表达式计算逻辑

2023-12-13 21:06:53
题目:

给出如下串:sum(sum(sum(1,2),avg(3,5)),avg(avg(6,8),7)), 计算结果(保证输入任意上述接口均能输出正确结果)

思路:
wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==?编辑
代码:
import java.util.Stack;

public class Test {
    public static String sum = "sum";
    public static String avg = "avg";
    public static String s1 = "sum(sum(sum(1,2),avg(3,5)),avg(avg(6,8),7))";

    public static void main(String[] args) {
        System.out.println(parseByStack(s1));;
    }
    
    /**
     * 
     * @param s
     * @return
     */
    public static float parseByStack(CharSequence s) {
        Stack<String> operators = new Stack<>();
        Stack<Float> numbers = new Stack<>();
        int index = 0;
        while (index < s.length()) {
            if (s.charAt(index) == 's' && s.charAt(index + 1) == 'u' && s.charAt(index + 2) == 'm') {
                operators.push(sum);
                index += 3;
            } else if (s.charAt(index) == 'a' && s.charAt(index + 1) == 'v' && s.charAt(index + 2) == 'g') {
                operators.push(avg);
                index += 3;
            } else if (Character.isDigit(s.charAt(index))) {
                StringBuilder sb = new StringBuilder();
                while (Character.isDigit(s.charAt(index))) {
                    sb.append(s.charAt(index));
                    index++;
                }
                numbers.push(Float.parseFloat(sb.toString()));
            } else if (s.charAt(index) == ')') {
                // 遇见左括号时,需要处理数据
                var operator = operators.pop();
                if (operator.equals(sum)) {
                    numbers.push(numbers.pop() + numbers.pop());
                } else if (operator.equals(avg)) {
                    numbers.push((numbers.pop() + numbers.pop()) / 2);
                }
                index++;
            } else {
                // s.charAt(index) == '(' || s.charAt(index) == ','
                index++;
            }
        }
        return numbers.pop();
    }
}

文章来源:https://blog.csdn.net/GAOXINXINGgaoxinxing/article/details/134973883
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。