栈和队列_8

文章介绍了如何解决LeetCode题目946,验证给定的pushed和popped序列是否可以通过一系列合法的栈操作得到。通过模拟入栈和出栈过程来判断序列的可行性。
摘要由CSDN通过智能技术生成


一、leetcode-946

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

输入
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


二、题解

1.引库

 #include <iostream>
 #include <cstdio>
 #include <cstdlib>
 #include <queue>
 #include <stack>
 #include <algorithm>
 #include <string>
 #include <map>
 #include <set>
 #include <vector>
 using namespace std;
 

2.代码

1.模拟入栈出栈,找到正确序列

class Solution {
public:
    bool validateStackSequences(vector<int>& pushed, vector<int>& popped) {
		int x=0,n=pushed.size();//x代表入栈位置下表 
		stack<int> s;
		for(int i=0;i<n;i++){
		 	if(s.empty()||s.top()!=popped[i]){
		 		while(x<pushed.size()&&pushed[x]!=popped[i]){
		 			s.push(pushed[x]);
		 			x++;
				}
				if(x==pushed.size()) return false;
				s.push(pushed[x]);//找到了pop序列中对应的元素 
				x++;
			}
			s.pop(); //其实可以不用入栈出栈,直接x++ 
		}
		return true;
    }
};
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值