目录
一只有一种括号(以圆括号举例)
#include<iostream>
#include <stack>
using namespace std;
bool ti2_1(string ch);
int main(){
while(true){
cout<<"请输入字符串(#结尾):";
string ch;
cin>>ch;
ti2_1(ch);
}
}
bool ti2_1(string ch)//判断括号匹配算法
{
stack<char> s;
//InitStack(s);
int i=0;
while(ch[i]!='#')
{
if(ch[i]=='(')
s.push(ch[i]);
if(ch[i]==')')
{
if(!s.empty())
s.pop();
else
return false;
}
i++;
}
if(s.empty()) {
cout<<"匹配成功"<<endl;
return true;
}
else {
cout<<"匹配失败"<<endl;
return false;
}
}
二:任何括号都可以
#include<iostream>
#include <stack>
using namespace std;
bool ti2_2(string ch);
int main(){
while(true){
cout<<"请输入字符串(#结尾):";
string ch;
cin>>ch;
ti2_2(ch);
}
}
bool ti2_2(string ch)//判断括号匹配算法
{
stack<char> s;
//InitStack(s);
ElemType x;
int i=0;
while(ch[i]!='#')
{
switch(ch[i])
{
case '(':
s.push(ch[i]);
break;
case '[':
s.push(ch[i]);
break;
case '{':
s.push(ch[i]);
break;
case ')':
{
if(s.empty())
return false;
else
{
x=s.pop();
if(x!='(')
return false;
}
break;
}
case ']':
{
if(s.empty())
return false;
else
{
x=s.pop();
if(x!='[')
return false;
}
break;
}
case '}':
{
if(s.empty())
return false;
else
{
x=s.pop();
if(x!='{')
return false;
}
break;
}
}
i++;
}
if(s.empty()) {
cout<<"匹配成功"<<endl;return true;
}
else {
cout<<"匹配失败"<<endl;return false;
}
}