编程 Java/c/c++帝国
http://ccnu.openjudge.cn/practice/1978/
#include <cstdio>
#include <stack>
#include <string>
using namespace std;
int main(){
char buf[200];
while(fgets(buf, 200, stdin) != NULL){
//使用fgets配合while实现不确定数量的多行读取
string str = buf;
str.pop_back(); //str去掉了额外的换行
stack<unsigned> indexStack; //存储左圆括号的下标
string res; //存储输出结果
for(unsigned i = 0; i < str.size(); ++i){
if(str[i] == '('){
indexStack.push(i); //左圆括号下标压栈
//姑且认为是非法的
res.push_back('$');
}
else if(str[i] == ')'){
if(indexStack.empty()){
res.push_back('?');
}
else{
res.push_back(' '); //此右圆括号合法
res[indexStack.top()] = ' '; //之前假设为非法的左圆括号改为合法
indexStack.pop(); //匹配成功的左圆括号下标弹栈
}
}
else{
res.push_back(' ');
}
}
printf("%s\n", str.c_str());
printf("%s\n", res.c_str());
}
}
样例输入
((ABCD(x)
)(rttyy())sss)(
样例输出
((ABCD(x)
$$
)(rttyy())sss)(
? ?$