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

题目:

给出如下串: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();
    }
}

相关推荐

  1. 数据结构---栈(Stack)

    2023-12-14 05:52:04       63 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2023-12-14 05:52:04       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2023-12-14 05:52:04       100 阅读
  3. 在Django里面运行非项目文件

    2023-12-14 05:52:04       82 阅读
  4. Python语言-面向对象

    2023-12-14 05:52:04       91 阅读

热门阅读

  1. EFK 部署(一次成功)并且验证测试

    2023-12-14 05:52:04       52 阅读
  2. 物联网架构之CDH

    2023-12-14 05:52:04       43 阅读
  3. Tomcat指定jdk启动

    2023-12-14 05:52:04       51 阅读
  4. Narak

    Narak

    2023-12-14 05:52:04      52 阅读
  5. 网络安全学习之信息泄露

    2023-12-14 05:52:04       65 阅读
  6. 在Nexus上配置Docker镜像仓库

    2023-12-14 05:52:04       49 阅读