求合法的出栈序列 (附上 leetcode946. 验证栈序列 )

已知从1~n的数字序列,按顺序出栈。每一个数字入栈后有两种选择:1-当即出栈,2-等待后面的数字入栈出栈后,该数字再出栈。ios

如今给出一个数字序列,求该数字序列是否合法?c++

#include<iostream>
#include<algorithm>
#include<vector>
#include<bits/stdc++.h>

using namespace std;
class MinStack {
public:
	stack<int> a;
	stack<int> Min;
	MinStack() {
	}
	void push(int n) {
		if (a.size() == 0) {
			a.push(n);
			Min.push(n);
		}
		else {
			a.push(n);
			if (n < Min.top()) {
				Min.push(n);
			}
			else {
				Min.push(Min.top());
			}
		}

	}
	int pop() {
		int num = a.top();
		a.pop();
		Min.pop();
		return num;
	}
	int getMin() {		
		return Min.top();
	}
	bool empty() {
		return a.empty();
	}
	int size() {
		return a.size();
	}
};
bool bringin(vector<int>& aa, stack<int>& a) {//入栈函数
	if (!aa.empty()) {
		a.push(aa[0]);
		aa.erase(aa.begin());
		return true;
	}
	else {
		return false;
	}
}

bool ceshi(vector<int> &aa,stack<int> &a) {//测试函数
	string s;
	cin >> s;//输入你想测试的数字序列
	int i;
	if (bringin(aa, a) == false)//一开始的栈就是空的,因此第一步确定要先让栈有元素,若是初始序列为空,那么直接返回flase
		return false;
	else {
		for (i = 0; i < s.size(); i++) {
			while (a.empty() || a.top() != (s[i] - '0')) {//必定不要弄错顺序,要先判断栈是否为空,若为空,固然要进行入栈操做
				if (bringin(aa, a) == false)
					return false;
			}
			if (a.top() == (s[i] - '0')) {//栈顶元素和判断位置的序列一致的话,就出栈。
				a.pop();
			}
		}
	}
	if (i == s.size())//完美匹配上全部数字序列,返回true
		return true;
	else 
		return false;
	
}
int main() {
	stack<int> a;
	vector<int> aa = { 1,2,3,4,5 };//初始序列
	cout << ceshi(aa, a);
	return 0;

}

在这里插入图片描述
计算机绘图技术较差,望见谅。web

主要就是 栈顶元素s[ i ] 匹配,不一样就继续入栈,相同就出栈。svg

细节上,多多考虑栈空时须要进行什么操做便可。函数

.
.
.
.测试

946.验证栈序列 (leetcode)

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

示例 1:code

输入: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() -> 1xml

示例 2:blog

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

class Solution {
public:
    bool validateStackSequences(vector<int>& pushed, vector<int>& popped) {
        stack<int> a;
        for(int i =0;i<popped.size();i++){
            while((a.empty()||a.top()!=popped[i])&&!pushed.empty()){
                a.push(pushed[0]);
                pushed.erase(pushed.begin());
            }
            if(a.top()==popped[i]){
                a.pop();
            }
        }
        if(a.size() == 0)
            return true;
        else
            return false;
    }
};