题解 | 验证栈序列

验证栈序列

https://www.nowcoder.com/practice/d3178fe362dd4810b577c77c9e128fc5

import java.util.*;
public class Main{
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        int q = in.nextInt();
        while(q-->0){
            int n = in.nextInt();
            int[] a = new int[n],b = new int[n];
            for(int i=0;i<n;i++)a[i] = in.nextInt();
            for(int i=0;i<n;i++)b[i] = in.nextInt();
            Deque<Integer> stack = new ArrayDeque<>();
            int cur = 0;
            for(int i:a){
                stack.push(i);
                //用一个栈来模拟出栈过程,只要栈顶元素与出栈序列元素相同就出栈
                //,并移动出栈序列指针
                while(!stack.isEmpty()&&stack.peek()==b[cur]){
                    stack.pop();
                    cur++;
                }
            }
            if(stack.isEmpty()){
                System.out.println("Yes");
            }
            else{
                System.out.println("No");
            }
        }
    }
}

全部评论

相关推荐

joecii:如果没有工资,那可能没有工资是这家公司最小的问题了
找实习记录
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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