题解 | #矩阵乘法计算量估算#
矩阵乘法计算量估算
http://www.nowcoder.com/practice/15e41630514445719a942e004edc0a5b
-
1、字符 是左括号,什么也不做
-
2、字符 是右括号,出栈
-
3、字符 是非括号,入栈
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.hasNextLine()) { // 注意 while 处理多个 case
String ll = in.nextLine();
int n = Integer.parseInt(ll);
int[][] juzhen = new int[n][2];
for (int i= 0; i < n; i++) {
String[] temp = in.nextLine().split(" ");
juzhen[i][0] = Integer.parseInt(temp[0]);
juzhen[i][1] = Integer.parseInt(temp[1]);
}
String faze = in.nextLine();
System.out.println(function(juzhen, faze));
}
}
public static int function(int[][] juzhen, String yusuan) {
int result = 0;
Stack<int[]> stack = new Stack<>();
for (int i = 0; i < yusuan.length(); i++) {
if (yusuan.charAt(i) == '(') {
} else if (yusuan.charAt(i) == ')') {
int[] lastjuzhen = stack.pop();
int[] nearjuzhen = stack.pop();
result = result + lastjuzhen[0] * lastjuzhen[1] * nearjuzhen[0];
stack.push(new int[] {nearjuzhen[0], lastjuzhen[1]});
} else {
stack.push(juzhen[yusuan.charAt(i) - 'A']);
}
}
return result;
}
}