zoukankan      html  css  js  c++  java
  • [leetcode]946. Validate Stack Sequences用Stack验证序列

    Given two sequences pushed and popped with distinct values, return true if and only if this could have been the result of a sequence of push and pop operations on an initially empty stack.

    Example 1:

    Input: pushed = [1,2,3,4,5], popped = [4,5,3,2,1]
    Output: true
    Explanation: We might do the following sequence:
    push(1), push(2), push(3), push(4), pop() -> 4,
    push(5), pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1

    Example 2:

    Input: pushed = [1,2,3,4,5], popped = [4,3,5,1,2]
    Output: false
    Explanation: 1 cannot be popped before 2.

    Note:

    1. 0 <= pushed.length == popped.length <= 1000
    2. 0 <= pushed[i], popped[i] < 1000
    3. pushed is a permutation of popped.
    4. pushed and popped have distinct values.

    题意

    给定两个序列push[]、popped[]。 用Stack验证用两个序列的元素,经过一番push和pop操作, Stack能为空

    Solution: Stack

    code

     1 class Solution {
     2     public boolean validateStackSequences(int[] pushed, int[] popped) {
     3         Stack<Integer> stack = new Stack<>();
     4         int i = 0;
     5         for (int p : pushed) {
     6             stack.push(p);
     7             while (!stack.isEmpty() && stack.peek() == popped[i]) {
     8                 stack.pop();
     9                 ++i;
    10             }
    11         }
    12         return stack.empty();
    13     }
    14 }
  • 相关阅读:
    一:多线程--多线程简单介绍
    五:网络--多线程断点下载
    四:网络--NSURLConnection基本使用
    三:网络--数据安全/加密
    二:网络--GET请求和POST请求
    一:网络--HTTP协议
    源代码管理工具GIT
    MyBatis 多参问题
    jquery 事件
    jquery点击事件
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/10873360.html
Copyright © 2011-2022 走看看