7-13 符号配对 (20 分)

7-13 符号配对 (20 分)
在取st.top()之前,记得先判断 !st.empty()噢~
否则出现段错误

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

int main(){//getline(cin,s)按行读 
	string s;
	stack<char> st;
	while(!st.empty())st.pop();
	int flag=0;
	char w;
//	int dir;
	while(getline(cin,s)){
		int len=s.size();//字符串数组长度时strlen(s) 
		if(s[0]=='.'&&!s[1])break;
		for(int i=0;!flag&&i<len;i++){
			if(s[i]=='('||s[i]=='['||s[i]=='{'){
				st.push(s[i]);
			}
			else if(i<(len-1)&&s[i]=='/'&&s[i+1]=='*'){
				st.push('#');
//				if(i<(len-2)&&s[i+2]=='/'){
//					flag=1;
					w='#';
//				}
//不用额外考虑/*/啦,i++加上外层循环的i++,跳过了/*,即使后来有/也构不成 
				i++;
			}
			else if(s[i]==')'){
				if(!st.empty()&&st.top()=='(')st.pop();
				else{
					flag=1;
					w=')';
				}
			}
			else if(s[i]==']'){
				if(!st.empty()&&st.top()=='[')st.pop();
				else{
					flag=1;
					w=']';
				}
			}
			else if(s[i]=='}'){
				if(!st.empty()&&st.top()=='{')st.pop();
				else{
					flag=1;
					w='}';
				}
			}
			else if(i<(len-1)&&s[i]=='*'&&s[i+1]=='/'){
				i++;
				if(!st.empty()&&st.top()=='#')st.pop();
				else{
					flag=1;
					w='#';
				}
			}
			
		}
	} 
	if(!flag&&st.empty()){
		cout<<"YES";
		return 0;
	}
	else cout<<"NO"<<endl;
	if(flag){
		if(!st.empty()){
			char ch=st.top();
	 	    if(ch=='#')cout<<"/*-?"; 
			else cout<<ch<<"-?";
		}
		else{
			if(w=='#')cout<<"?-*/";
			else cout<<"?-"<<w;
		}
	}
	else{
		char ch=st.top();
	 	    if(ch=='#')cout<<"/*-?"; 
			else cout<<ch<<"-?";
	}

    return 0;
}
 //一开始没判断栈空,一来段错误,二来对于 /*/,
//既然判断栈空,那么可以一同监测, 如果遇到右括号而栈为空了直接判断
//而不用,这么说吧,想想这个例子 输入只有')', 按照先前代码 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值