括号匹配的检验
描述:
假设一个表达式或一段程序中含有三种括号:圆括号“(”和“)”、方括号“[”和“]”、花括号“{”和“}”。试写一个程序判别给定的表达式或程序中所含括号是否正确配对出现。
输入说明:
每行为一个含有括号的表达式或一段程序。
输出说明:
输出一个right或wrong,表明正确匹配与否。
输入样例:
while (m<(a[8]+t) {m=m+1; t=t-1;}
输出样例:
wrong
提示
用栈来实现
———————————————————————————————————————————
写题过程中遇到的问题:
1.如何输入带有空格的字符串:
string str;
getline(cin,str);
2.遇到 ')'、'}'、']' 时判断栈顶元素是否为前括号时,可能会出现栈顶元素不存在的情况,需先判定栈顶元素存在。否则例如“ }}} ” 则无法输出结果。
3.循环结束后需判断栈是否为空,若栈不为空,则还剩余前括号,匹配结果为wrong。若栈为空,则匹配正确。
源码如下:
#include<iostream>
#include<stack>
#include<string>
using namespace std;
int main() {
string s;
stack<char> st;
getline(cin,s);//注意点1
int j=0;
while(j<s.size()) {
char x=s[j];
j++;
if(x=='('||x=='{'||x=='[') {
st.push(x);
} else if(x==')') {
if(st.size()>0&&st.top()=='(') {//注意点2
st.pop();
} else {
cout<<"wrong";
return 0;
}
} else if(x==']') {
if(st.size()>0&&st.top()=='[') {
st.pop();
} else {
cout<<"wrong";
return 0;
}
} else if(x=='}') {
if(st.size()>0&&st.top()=='{') {
st.pop();
} else {
cout<<"wrong";
return 0;
}
}
}
if(st.size()==0)//注意点3
cout<<"right";
else
cout<<"wrong";
return 0;
}