说明:
栈只保存左括号的下标,由于是下标所以可以进行恢复,确保在正确的位置重新判断,右括号及时判断,存入判断符于ans数组。
#include<stdio.h>
#include<stack>
using namespace std;
stack<int> S;
char str[110];
char ans[110];
int main(){
while(scanf("%s",&str) != EOF){
int i;
for(i = 0;str[i]!=0;i++){
if(str[i]=='('){
S.push(i);//存下标
ans[i] = ' ';
}
else if(str[i]==')'){
if(S.empty()==false){
S.pop();
ans[i] = ' ';
}
else ans[i] = '?';
}
else ans[i] = ' ';
}
while(!S.empty()){
int t = S.top();
ans[t] = '$';
S.pop();
}
ans[i] = 0;
puts(str);
puts(ans);
}
}
结果: