王道计试例题5.5 括号匹配问题
#include<iostream>
#include<stack>
#include<string>
using namespace std;
// )(rttyy())sss)(
int main(){
string str1;
while(getline(cin, str1)){// 获取输入
cout<<str1<<endl;
stack<char> MyStack;
stack<int> IndexStack;
string str2;
for(int i = 0; i < str1.size(); i++){
str2 += " ";
}
for(int i = 0; i < str1.size(); i++){
char target = str1[i];
if(target == '('){
// 左括号直接入栈
MyStack.push(target);
IndexStack.push(i);
} else if (target == ')'){
if(MyStack.empty()){ // 不能匹配的右括号
str2[i] = '?';
} else if(MyStack.top() == '('){// 右括号与左括号消去
MyStack.pop();
IndexStack.pop();
} else { // 不能匹配的右括号
str2[i] = '?';
}
} else {
str2[i] = ' ';
}
}
// 寻找不能匹配的左括号
int size = IndexStack.size();
int index;
for(int i = 0; i < size; i++){
index = IndexStack.top();
IndexStack.pop();
str2[index] = '$';
}
cout<<str2<<endl;
}
}#牛客AI配图神器#
#include<stack>
#include<string>
using namespace std;
// )(rttyy())sss)(
int main(){
string str1;
while(getline(cin, str1)){// 获取输入
cout<<str1<<endl;
stack<char> MyStack;
stack<int> IndexStack;
string str2;
for(int i = 0; i < str1.size(); i++){
str2 += " ";
}
for(int i = 0; i < str1.size(); i++){
char target = str1[i];
if(target == '('){
// 左括号直接入栈
MyStack.push(target);
IndexStack.push(i);
} else if (target == ')'){
if(MyStack.empty()){ // 不能匹配的右括号
str2[i] = '?';
} else if(MyStack.top() == '('){// 右括号与左括号消去
MyStack.pop();
IndexStack.pop();
} else { // 不能匹配的右括号
str2[i] = '?';
}
} else {
str2[i] = ' ';
}
}
// 寻找不能匹配的左括号
int size = IndexStack.size();
int index;
for(int i = 0; i < size; i++){
index = IndexStack.top();
IndexStack.pop();
str2[index] = '$';
}
cout<<str2<<endl;
}
}#牛客AI配图神器#
全部评论
相关推荐
ohs的小木屋:卷java后端有点难,试试其他方向呢


点赞 评论 收藏
分享