【剑指】31.栈的压入、弹出序列

题目描述

  • 输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1、2、3、4、5是某栈的压栈序列,序列4、5、3、2、1是该压栈序列对应的一个弹出序列,但4、3、5、1、2就不可能是该压栈序列的弹出序列。

算法分析

  • 借用一个辅助的栈,遍历压栈顺序,先将第一个元素压入栈中,这里是1,然后判断栈顶元素是不是出栈顺序的第一个元素,这里是4,很显然1≠4,所以我们继续压栈,直到相等以后开始出栈;出栈一个元素,则将出栈顺序向后移动一位,直到不相等,这样循环等压栈顺序遍历完成,如果辅助栈还不为空,说明弹出序列不是该栈的弹出顺序。

提交代码:

class Solution {
public:
	bool IsPopOrder(vector<int> pushV, vector<int> popV) {
		stack<int> stackV;

		if (pushV.empty() || popV.empty() || pushV.size() != popV.size())
			return false;

		for (int i = 0, j = 0; i < pushV.size(); ++i)
		{
			stackV.push(pushV[i]);
			while (j < pushV.size() && stackV.top() == popV[j])
			{
				stackV.pop();
				++j;
			}	
		}

		if (stackV.empty())
			return true;
		
		return false;
	}
};

测试代码:

// ====================测试代码====================
void Test(const char* testName, vector<int> &pPush, vector<int> &pPop, bool expected)
{
	if (testName != nullptr)
		printf("%s begins: ", testName);

	Solution s;
	if (s.IsPopOrder(pPush, pPop) == expected)
		printf("Passed.\n");
	else
		printf("failed.\n");
}

void Test1()
{
	vector<int> push = { 1, 2, 3, 4, 5 };
	vector<int> pop = { 4, 5, 3, 2, 1 };

	Test("Test1", push, pop, true);
}

void Test2()
{
	vector<int> push = { 1, 2, 3, 4, 5 };
	vector<int> pop = { 3, 5, 4, 2, 1 };

	Test("Test2", push, pop, true);
}

void Test3()
{
	vector<int> push = { 1, 2, 3, 4, 5 };
	vector<int> pop = { 4, 3, 5, 1, 2 };

	Test("Test3", push, pop, false);
}

void Test4()
{
	vector<int> push = { 1, 2, 3, 4, 5 };
	vector<int> pop = { 3, 5, 4, 1, 2 };

	Test("Test4", push, pop, false);
}

// push和pop序列只有一个数字
void Test5()
{
	vector<int> push = { 1 };
	vector<int> pop = { 2 };

	Test("Test5", push, pop, false);
}

void Test6()
{
	vector<int> push = { 1 };
	vector<int> pop = { 1 };

	Test("Test6", push, pop, true);
}

void Test7()
{
	Test("Test7", vector<int>(), vector<int>(), false);
}

int main(int argc, char* argv[])
{
	Test1();
	Test2();
	Test3();
	Test4();
	Test5();
	Test6();
	Test7();

	return 0;
}


猜你喜欢

转载自blog.csdn.net/ansizhong9191/article/details/80943255