利用队列Queue或栈Stack解决字符数组转换运算题

一、题目
给定包含特殊运算符号@,$ ,转换规则如下
x@y=2x+y+3
x$y =3x+2y+1
其中x,y都是非负整数且@优先级高于 $。

相同的特殊运算符,从左到右顺序计算。用例保证@,$,左右一定存在数字,且数字不存在前导为0。
输入

11@2$3@14

结果

128

二、算法实现
方法1

public static int getMatchResult(String information) {
        Queue<Integer> queue = new LinkedList<>();
        // 从$切分,注意转义
        String[] info = information.split("\\$");
        for (String s : info) {
            if (s.contains("@")) {
                String[] split = s.split("@");
                int n1 = Integer.parseInt(split[0]);
                int simple = 0;
                for (int i = 1; i < split.length; i++) {
                    simple = 2 * n1 + Integer.parseInt(split[i]) + 3;
                    n1 = simple;
                }
                queue.add(simple);
            } else {
                queue.add(Integer.valueOf(s));
            }
        }

        if (queue.size() == 1) {
            return queue.peek();
        }

        int count = 0;
        // 获取并移除队首元素
        int temp = queue.poll();
        while (!queue.isEmpty()) {
            count = 3 * temp + 2 * queue.poll() + 1;
            temp = count;
        }
        return count;
    }

方法2
利用流式计算,更加简洁

 public static int getMatchResult2(String information) {
        // 从$切分,注意转义
        String[] exp = information.split("\\$");
        List<Integer> expFinal = new ArrayList<>();
        for (String s : exp) {
            if (s.contains("@")) {
                String[] split = s.split("@");
                expFinal.add(Arrays.stream(split).map(Integer::new).reduce((a, b) -> 2 * a + b + 3).orElse(0));
            } else {
                expFinal.add(Integer.valueOf(s));
            }
        }

        return expFinal.stream().reduce((a, b) -> 3 * a + 2 * b + 1).orElse(0);
    }
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值