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;
}
//一开始没判断栈空,一来段错误,二来对于 /*/,
//既然判断栈空,那么可以一同监测, 如果遇到右括号而栈为空了直接判断
//而不用,这么说吧,想想这个例子 输入只有')', 按照先前代码