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

矩阵乘法计算量估算

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

import java.io.IOException;
import java.util.*;

public class Main {
    public static void main(String[] args) throws IOException, InterruptedException {
        Scanner sc = new Scanner(System.in);
        int count = Integer.parseInt(sc.nextLine());
        String[] input = new String[count];
        for(int i = 0; i < count; ++i){
            input[i] = sc.nextLine();
        }
        String expression = sc.nextLine();
        Stack<String> stack = new Stack();
        int result = 0;
        for (int i = 0, j = 0; i < expression.length(); ++i) {
            char c = expression.charAt(i);
            if(c == '('){
                // 遇到左括号,左括号入栈
                stack.push(c + "");
            } else if(Character.isLetter(c)){
                // 遇到字母,对应的矩阵大小入栈
                stack.push(input[j++]);
            }else {
                // 遇到右括号,计算结果并入栈
                String matrix2 = stack.pop();
                String matrix1 = stack.pop();
                if(stack.peek().equals("(")){
                    stack.pop();
                }
                stack.push(matrix1.split(" ")[0] + " " + matrix2.split(" ")[1]);
                result += Integer.parseInt(matrix1.split(" ")[0]) * Integer.parseInt(matrix1.split(" ")[1]) * Integer.parseInt(matrix2.split(" ")[1]);
            }
        }
        System.out.println(result);
    }
}

全部评论

相关推荐

2025-12-18 11:59
广州南方学院 C++
牛客78682892...:直接点还好,总比要了简历也不回的强
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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