题解 | 矩阵乘法计算量估算

矩阵乘法计算量估算

https://www.nowcoder.com/practice/15e41630514445719a942e004edc0a5b

  1. 狐假虎威,还以为是动态规划,原来是括弧匹配;还以为是复杂的栈操作,原来就是两两就近合并。
  2. 都在注解中,上代码~

import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = Integer.parseInt(in.nextLine());
        int[][] data = new int[n][2];
        for (int i = 0; i < n; i++) {
            String[] line = in.nextLine().split(" ");
            data[i][0] = Integer.parseInt(line[0]);
            data[i][1] = Integer.parseInt(line[1]);
        }
        long num = 0;
        String order = in.nextLine();
        Stack<int[]> stack = new Stack<>();
        int alphaIndex = 0;
        for (int i = 0; i < order.length(); i++) {
            char ch = order.charAt(i);
            if (ch == '(') {
                // 都不用入栈
                continue;
            }
            if (Character.isAlphabetic(ch)) {
                //是字母
                stack.push(new int[]{alphaIndex, alphaIndex});
                alphaIndex++;
                continue;
            }
            // ')' 触发计算
            int[] to = stack.pop();
            int[] from = stack.pop();
            // 把计算之后的新的(from,to)入栈
            stack.push(new int[]{from[0], to[1]});
            int a = data[from[0]][0];
            int b = data[from[1]][1];
            int c = data[to[1]][1];
            num += ((long) a * b * c);
        }
        System.out.println(num);
    }
}

#你都用vibe coding做过什么?##AI Coding实战技巧#
常规算法题目专栏 文章被收录于专栏

这里记录一些常规的算法题目题解,主要包括中等难度,还有一些有意思的题目~

全部评论
接好运
点赞 回复 分享
发布于 04-02 23:21 上海

相关推荐

最喜欢秋天的火龙果很...:第一份工作一定要往大的去,工资低点没事。后面换工作会更好找,即使你去小公司,你也不可能不会换工作的。所以找大的去
点赞 评论 收藏
分享
03-02 08:18
集美大学 Java
钱嘛数字而已:没有赛事奖项么?另外,项目经历字有点多哈,建议突出一下重点:用的什么技术,解决什么问题,达到什么效果。
大家都开始春招面试了吗
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

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