栈的压入、弹出序列
输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。(注意:这两个序列的长度是相等的)
#include "stdafx.h"
#include <string>
using namespace std;
#include<stack>
#include <vector>
实现 栈的压入、弹出序列
class Solution
{
public:
bool IsPopOrder(vector<int> pushA, vector<int> popA)
{
if (pushA.size() == 0 || popA.size() == 0)
{
return false;
}
for (int i = 0, j = 0; i < pushA.size(); i++)
{
st.push(pushA[i]);
if (j < popA.size() && st.top() == popA[j])
{
st.pop();
}
}
return st.empty();
}
Solution();
~Solution();
private:
stack <int> st;
};
Solution::Solution()
{
}
Solution::~Solution()
{
}
int main()
{
Solution sou;
vector<int> aa = { 1, 2, 3, 4, 5 };
vector<int> bb = { 4, 3, 5, 1, 2 };
bool bRet = sou.IsPopOrder(aa, bb);
return 1;
}
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步