#include <iostream>
#include <stack>
#include <string>
using namespace std;
bool solve(string s){
stack<char> st;
int i=0;
while(i<s.length()){
if(s[i]=='('||s[i]=='['||s[i]=='{')//左括号都入栈
st.push(s[i]);
else if(s[i]==')'){
if(st.top()=='(')
st.pop();//匹配就出栈
else
return false;
}
else if(s[i]=='}'){
if(st.top()=='{')
st.pop();
else
return false;
}
else if(s[i]==']'){
if(st.top()=='[')
st.pop();
else
return false;
}
i++;
}
if(st.empty())
return true;
else
return false;
}
int main(){
cout<<"匹配情况是:"<<endl;
string s="(a+[b-c]+d)";
cout<<s<<(solve(s)?"匹配":"不匹配")<<endl; //使用问号表达式输出是否匹配与否的结果
s="(a+[b-c}+d)";
cout<<s<<(solve(s)?"匹配":"不匹配")<<endl;
return 0;
}
检查括号(){}[]是匹配
于 2024-11-04 22:09:16 首次发布