【数据结构习题】7-1 符号配对 (20 分) 请编写程序检查C语言源程序中下列符号是否配对:/*与*/、(与)、[与]、{与}。

数据结构要了我的老命真的

7-1 符号配对 (20 分)
请编写程序检查C语言源程序中下列符号是否配对://、(与)、[与]、{与}。

输入格式:
输入为一个C语言源程序。当读到某一行中只有一个句点.和一个回车的时候,标志着输入结束。程序中需要检查配对的符号不超过100个。

输出格式:
首先,如果所有符号配对正确,则在第一行中输出YES,否则输出NO。然后在第二行中指出第一个不配对的符号:如果缺少左符号,则输出?-右符号;如果缺少右符号,则输出左符号-?。

输入一:
void test()
{
int i, A[10];
for (i=0; i<10; i++) /*/
A[i] = i;
}
.

输出一:
NO
/*-?

输入二:
void test()
{
int i
double A[10];
for (i=0; i<10; i++) /**/
A[i] = 0.1*i;
}
.

输出二:
YES

救命,可以说完全毫无头绪,我数据结构简直学了个蛇5555
搬上仔细研读过后的别人的代码SOS

#include<bits/stdc++.h>
using namespace std;
int main() 
{
	stack<string> st;
	string s;
	string res;
	while(1) 
	{
		getline(cin,s);
		if(s==".")
			break;
		res=res+s;
	}

	for(int i=0;i<res.length();i++) 
	{
		if(res[i]=='/'&&res[i+1]=='*'&&(i+1<res.length()))
		{
			st.push(res.substr(i,2));//获得字符串res中从第i位开始的长度为2的字符串
			i++;
		}
		
		else if(res[i]=='*'&&res[i+1]=='/'&&(i+1<res.length()))
		{
			if(!st.empty()&&st.top()=="/*")
				// 若为*/,且栈不为空,栈内还有/*与之配对,则/*出栈
				st.pop();//出栈
			else
				//若没有的话,配对失败,按照题目要求输出
			{
				cout<<"NO"<<endl;
				if(st.empty()) //如果栈为空 
					cout<<"?-*/";
				//缺少左符号
				else
					cout<<st.top()<<"-?";
				//栈内的符号没有配对成功
				return 0;
			}
			i++;
		}

		else if(res[i]=='('||res[i]=='{'||res[i]=='[') 
		{
			st.push(string(1,res[i])); //用1个字符res[i]初始化
		}

		else if(res[i]=='}') 
		{
			if(!st.empty()&&st.top()=="{")
				st.pop();
			else 
			{
				cout<<"NO"<<endl;
				if(st.empty())
					cout<<"?-"<<res[i];
				else
					cout<<st.top()<<"-?";
				return 0;
			}
		} 
		
		else if(res[i]==']') 
		{
			if(!st.empty()&&st.top()=="[")
				st.pop();
			else 
			{
				cout<<"NO"<<endl;
				if(st.empty())
					cout<<"?-"<<res[i];
				else
					cout<<st.top()<<"-?";
				return 0;
			}
		}

		else if(res[i]==')') 
		{
			if(!st.empty()&&st.top()=="(")
				st.pop();
			else 
			{
				cout<<"NO"<<endl;
				if(st.empty())
					cout<<"?-"<<res[i];
				else
					cout<<st.top()<<"-?";
				return 0;
			}
		}
	}
	
	if(st.empty())
		cout<<"YES";
	else 
	{
		cout<<"NO"<<endl;
		cout<<st.top()<<"-?";
	}
	return 0;
}

用到的函数详解
1、substr()函数
2、string(1,res[i]) 这玩意我还是没搞懂是个啥

  • 6
    点赞
  • 32
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值