嵌入式实习笔面试第三弹

美团3.25笔试第一题,模拟栈

这道题我的思路一开始是清晰的,但到后面因为调试了太长时间,脑子已经乱了

我的源代码如下

#include <iostream>
#include <algorithm>
#include <stack>
#include <string>
#include <vector>
using namespace std;
int main()
{
	int h,x,y,z;
	int l = 0;
	cin >> h;
	stack<int> stackfirst;
	vector<int> num;
	vector<int> stackbaocun;
	vector<int> bijiao;
	for (int i = 0; i < h; i++)
	{
		cin >> x;
		for (int j = 0; j < x; j++)
		{
			cin >> y;
			cin >> z;
			stackfirst.push(y);
			stackbaocun.push_back(y);
			bijiao.push_back(z);	
		}
		while (!stackfirst.empty()) {
			int temp = stackfirst.top();
			cout << temp;
			stackfirst.pop();
		}
		if (stackbaocun[l++] == bijiao[l++])
		{
			printf("Yes");
		}
		else {
			printf("No");
		}
	}
	
	/*cout << stackfirst.size() << endl;
	cout << bijiao.size() << endl;
	
	while (!stackfirst.empty()) {
		int temp = stackfirst.top();
		cout << temp;
		stackfirst.pop();
	}

	return 0;
}

chatgpt居然都没有看出来这段代码的用途,所以确实错的很离谱

 之后我让chatgpt完善一下这段代码,主要完成功能为根据一个数字1到n的入栈顺序in[]和出栈顺序out[],问这个出入栈顺序是否合法

代码如下:

#include <iostream>
#include <stack>
#include <vector>
using namespace std;

int main()
{
	int n;
	cin >> n;
	vector<int> in(n);
	vector<int> out(n);
	for (int i = 0; i < n; i++) {
		cin >> in[i];
	}
	for (int i = 0; i < n; i++) {
		cin >> out[i];
	}

	stack<int> s;
	int i = 0, j = 0;
	while (i < n) {
		s.push(in[i++]);
		while (!s.empty() && s.top() == out[j]) {
			s.pop();
			j++;
		}
	}
	if (s.empty()) {
		cout << "Yes" << endl;
	}
	else {
		cout << "No" << endl;
	}

	return 0;
}

美团的需求需要加入组数,改动后代码如下:
 

#include <iostream>
#include <stack>
#include <vector>
using namespace std;

void solve()
{
	int n;
	cin >> n;
	vector<int> in(n);
	vector<int> out(n);
	for (int i = 0; i < n; i++) {
		cin >> in[i];
	}
	for (int i = 0; i < n; i++) {
		cin >> out[i];
	}

	stack<int> s;
	int i = 0, j = 0;
	while (i < n) {
		s.push(in[i++]);
		while (!s.empty() && s.top() == out[j]) {
			s.pop();
			j++;
		}
	}
	if (s.empty()) {
		cout << "Yes" << endl;
	}
	else {
		cout << "No" << endl;
	}
}
int main()
{
	int l;
	cin >> l;
	
	for (int i = 0; i < l; i++) {
		solve();
	}

	return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值