7-5 括号匹配
给定一串字符,不超过100个字符,可能包括括号、数字、字母、标点符号、空格,编程检查这一串字符中的( ) ,[ ],{ }是否匹配。
输入格式:
输入在一行中给出一行字符串,不超过100个字符,可能包括括号、数字、字母、标点符号、空格。
输出格式:
如果括号配对,输出yes,否则输出no。
输入样例1:
sin(10+20)
输出样例1:
yes
输入样例2:
{[}]
输出样例2:
no
#include<iostream>
using namespace std;
typedef struct {
char* top;
char* base;
int stacksize;
}SqStack;
int Initstack(SqStack& s)
{
s.base = new char[105];
if (!s.base)
return 0;
s.top = s.base;
s.stacksize = 105;
return 1;
}
int push(SqStack& s, char e)
{
if (s.top - s.base >= s.stacksize)
return 0;
*s.top = e;
s.top++;
return 1;
}
int pop(SqStack& s)
{
if (s.top == s.base)
return 0;
s.top--;
return 1;
}
int stackEmpty(SqStack& s)
{
if (s.top == s.base)
return 1;
else
return 0;
}
int matching(char * e)
{
int i=0;
SqStack s;
Initstack(s);
while(e[i])
{
if (e[i] == '(' || e[i] == '[' || e[i] == '{')
{
push(s,e[i]);
}
else if (e[i] == ']')
{
if (!stackEmpty(s))
{
if (*(s.top-1)== '[')
pop(s);
else
return 0;
}
else return 0;
}
else if (e[i] == ')')
{
if (!stackEmpty(s))
{
if (*(s.top-1)== '(')
pop(s);
else
return 0;
}
else return 0;
}
else if (e[i] == '}')
{
if (!stackEmpty(s))
{
if (*(s.top-1)== '{')
pop(s);
else return 0;
}
else return 0;
}
i++;
}
if (!stackEmpty(s))
return 0;
else
return 1;
}
int main()
{
char ch[105];
cin.getline(ch,105);
if (matching(ch))
cout<<"yes"<<endl;
else
cout<<"no"<<endl;
return 0;
}