rambless:栈➕递归

import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        int n = in.nextInt();
        List<int[][]> list = new ArrayList<>();
        for(int i=0; i<n; i++) {
            int x = in.nextInt();
            int y = in.nextInt();
            list.add(new int[x][y]);
        }
        in.nextLine();
        String s = in.nextLine();
        Deque<int[][]> stack = new LinkedList<>();
        System.out.println(cal(s, list, stack));
        //System.out.println((int)'A');
    }
    // 10*20*5 + 50*10*5
    private static int cal(String s, List<int[][]> list, Deque<int[][]> stack) {
        Deque<int[][]> queue = new LinkedList<>();
        char[] arr = s.toCharArray();
        int num = 0;
        for(int i=0; i<s.length(); i++) {
            if(arr[i]=='(') {
                int count = 1;
                int j = i+1;
                while(count>0) {
                    if(arr[j]=='(') {
                        count++;
                    } else if(arr[j]==')') {
                        count--;
                    }
                    j++;
                }
                num += cal(s.substring(i+1, j-1), list, stack);
                i = j-1;
                while(!stack.isEmpty()) {
                    queue.push(stack.pop());
                }
            } else {
                queue.push(list.get(arr[i]-65));
            }
        }
        
        int[][] t = queue.pollLast();
        while(!queue.isEmpty()) {
            int[][] a = queue.pollLast();
            num += t.length * t[0].length * a[0].length;
            t = new int[t.length][a[0].length];
        }
        stack.push(t);
        return num;
    }
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务