zoukankan      html  css  js  c++  java
  • Leetcode946. Validate Stack Sequences验证栈序列

    给定 pushed 和 popped 两个序列,只有当它们可能是在最初空栈上进行的推入 push 和弹出 pop 操作序列的结果时,返回 true;否则,返回 false 。

    示例 1:

    输入:pushed = [1,2,3,4,5], popped = [4,5,3,2,1] 输出:true 解释:我们可以按以下顺序执行: push(1), push(2), push(3), push(4), pop() -> 4, push(5), pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1

    示例 2:

    输入:pushed = [1,2,3,4,5], popped = [4,3,5,1,2] 输出:false 解释:1 不能在 2 之前弹出。

    提示:

    1. 0 <= pushed.length == popped.length <= 1000
    2. 0 <= pushed[i], popped[i] < 1000
    3. pushed 是 popped 的排列。

     class Solution {
     public:
    	 bool validateStackSequences(vector<int>& pushed, vector<int>& popped) 
    	 {
    		 stack<int> s;
    		 int len1 = pushed.size();
    		 int len2 = popped.size();
    		 if (len1 != len2)
    		 {
    			 return false;
    		 }
    		 int i = 0;
    		 int j = 0;
    		 while (i < len1 && j < len2)
    		 {
    			 s.push(pushed[i++]);
    			 while (!s.empty() && j < len2 && s.top() == popped[j])
    			 {
    				 j++;
    				 s.pop();
    			 }
    		 }
    		 if (j != len2 || !s.empty())
    			 return false;
    		 return true;
    	 }
     };
  • 相关阅读:
    169. Majority Element
    283. Move Zeroes
    1331. Rank Transform of an Array
    566. Reshape the Matrix
    985. Sum of Even Numbers After Queries
    1185. Day of the Week
    867. Transpose Matrix
    1217. Play with Chips
    766. Toeplitz Matrix
    1413. Minimum Value to Get Positive Step by Step Sum
  • 原文地址:https://www.cnblogs.com/lMonster81/p/10433785.html
Copyright © 2011-2022 走看看