题解 | #矩阵乘法计算量估算#,跟着大佬们又学习到了栈的用法

矩阵乘法计算量估算

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

import java.util.Scanner;
import java.util.Stack;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNextInt()) { // 注意 while 处理多个 case
            int n = in.nextInt();
            int[][] ints = new int[n][2];
            for (int i = 0; i < n; i++) {
                // 行数
                ints[i][0] = in.nextInt();
                // 列数
                ints[i][1] = in.nextInt();
            }
            String s = in.next();
            Stack<Integer> stack = new Stack<>();

            int count = 0;
            // 倒着遍历
            for (int i = s.length() - 1,j = n - 1; i >=0; i--) {
                char c = s.charAt(i);
                if (c >= 'A' && c <= 'Z'){
                    // 列
                    int y = ints[j][1];
                    // 行
                    int x = ints[j][0];
                    stack.push(y);
                    stack.push(x);
                    j--;
                    continue;
                }
                if (c == '('){
                    Integer x1 = stack.pop();
                    Integer y = stack.pop();
                    Integer x2 = stack.pop();
                    Integer z = stack.pop();
                    // 计算本次乘的数量
                    count += x1 * y * z;
                    // 添加计算后的列和行
                    stack.push(z);
                    stack.push(x1);
                }
            }
            System.out.println(count);
        }
    }
}

全部评论
点赞 回复 分享
发布于 2023-08-28 11:42 浙江

相关推荐

05-19 16:41
复旦大学 Python
ynq2126:我一直觉得现在考算法题没啥意义 真要选拔人才不如把公司实际项目中遇到的问题当成一系列场景题抛给求职者答 这才是能检测能力的东西
点赞 评论 收藏
分享
评论
3
1
分享

创作者周榜

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