table of Contents
Stack sequence verification
Given two sequences pushed and popped, only when they are likely to be carried out on the initial empty stack push push and pop operation sequence results pop, returns true; otherwise, returns 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 之前弹出。
提示:
0 <= pushed.length == popped.length <= 1000
0 <= pushed[i], popped[i] < 1000
pushed 是 popped 的排列。
answer
For \ (PUSHED element to push stack array variable, when \) stack stack = \ (popped end of the stack, pop out, removed simultaneously \) popped end of the stack (greedy match).
<?
class Solution {
/**
* @param Integer[] $pushed
* @param Integer[] $popped
* @return Boolean
*/
function validateStackSequences($pushed, $popped) {
$stack = [];
foreach($pushed as $v){
$stack[] = $v;
while( $stack && current($popped)==end($stack)){
array_pop($stack);
array_shift($popped);
}
}
if( $stack ) return false;
return true;
}
}
The results: by displaying details
When execution: 28 ms, defeated 100.00% of users in all PHP submission
Memory consumption: 14.7 MB, defeated 100.00% of users in all PHP submission