题解 | 验证栈序列-Java

验证栈序列

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

import java.util.Scanner;
import java.util.Stack;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int round = in.nextInt();
        for (int i = 1; i <= round; i++) {
            int length = in.nextInt();
            in.nextLine(); // 吸收换行符
            String[] arr1 = in.nextLine().split(" ");
            String[] arr2 = in.nextLine().split(" ");
            boolean result = ifValid(arr1, arr2);
            System.out.println(result ? "Yes" : "No");
        }
        in.close();
    }

    public static boolean ifValid(String[] pushArr, String[] popArr) {
        Stack<String> stack = new Stack<>();
        int popIndex = 0; // 记录出栈序列的当前位置

        for (String num : pushArr) {
            stack.push(num); // 先将当前元素入栈

            // 入栈后,检查栈顶是否与出栈序列当前元素匹配,匹配则弹出
            while (!stack.isEmpty() && stack.peek().equals(popArr[popIndex])) {
                stack.pop();
                popIndex++; // 移动出栈指针
            }
        }

        // 如果栈为空,说明所有元素都按规则弹出,即匹配
        return stack.isEmpty();
    }
}

全部评论

相关推荐

10-10 01:10
已编辑
深圳大学 测试开发
面了100年面试不知...:六月到九月,四个项目一个实习,是魔丸吗
投了多少份简历才上岸
点赞 评论 收藏
分享
用微笑面对困难:你出于礼貌叫了人一声大姐,大姐很欣慰,她真把你当老弟
点赞 评论 收藏
分享
评论
2
收藏
分享

创作者周榜

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