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

矩阵乘法计算量估算

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

括号内多个数据也可以正确解除答案。
看了前几个题解,评论都说 括号内有三个数据的时候,会出现错误。因此,在写的时候格外注意。
通过 一个放数据的栈 和一个放顺序的栈。来实现对括号内多个数据,也可以标识出来,并计算。


import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);

        while (in.hasNextInt()) {
//             矩阵个数
            int a = in.nextInt();
//             结果集
            Stack<Integer> stackInt = new Stack<Integer>();
            int[][] data = new int[a][2];
            for (int i = 0 ; i < a ; i ++) {
                for (int j = 0 ; j < 2 ; j ++) {
                    data[i][j] = in.nextInt();
                }
            }
            in.nextLine();
//             保存计算顺序
            char[] str = in.nextLine().toCharArray();
            Stack<Character> stack = new Stack<Character>();
//             计算结果
            int resInt = 0 ;
// 倒叙遍历计算顺序,并写入顺序栈stack中,和记录数据的数据栈stackInt中
            for (int i = str.length - 1 ; i >= 0 ; i --) {
//                 右括号这在顺序栈中写入
                if (str[i] == ')') {
                    stack.push(')');
//                     左括号则计算数据栈中的数据,并更新顺序栈中的值
                } else if (str[i] == '(') {

                    while (stack.peek() != ')' ) {
                        stack.pop();
                        if (stack.peek() != ')') {
                            int y = stackInt.pop();
                            int x = stackInt.pop();
                            int y1 = stackInt.pop();
                            int x2 = stackInt.pop();

                            resInt += (x * y * y1);
                            stackInt.push(x);
                            stackInt.push(y1);
                        }
                    }
                    stack.pop();
//             每次计算完括号内容,其实还会剩下一个计算完写入的内容,因此需要在顺序栈中添加一个数据的标识
                    stack.push('a');
//                     不是左右括号,则将数据写入到数据栈中,在顺序栈中添加一个标识a,标识随意,和括号区分出来即可
                } else {
                    stack.push('a');
                    int x = data[str[i] - 'A'][0];
                    int y = data[str[i] - 'A'][1];
                    stackInt.push(x);
                    stackInt.push(y);
                }
            }
// 上面计算完成之后,已经把括号中的内容计算完成,下面只需要顺序计算剩下中的数据即可。
            while (stackInt.size() != 2) {
                int y = stackInt.pop();
                int x = stackInt.pop();
                int y1 = stackInt.pop();
                int x2 = stackInt.pop();

                resInt += (x * y * y1);
                stackInt.push(x);
                stackInt.push(y1);
            }

            System.out.println(resInt);
        }
    }
}
#在找工作求抱抱#
全部评论

相关推荐

点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
正在热议
更多
牛客网
牛客企业服务