2-1 括号匹配 (60分)
给定一串字符,不超过100个字符,可能包括括号、数字、字母、标点符号、空格,编程检查这一串字符中的( ) ,[ ],{ }是否匹配。
输入格式:
输入在一行中给出一行字符串,不超过100个字符,可能包括括号、数字、字母、标点符号、空格。
输出格式:
如果括号配对,输出yes,否则输出no。
输入样例1:
sin(10+20)
输出样例1:
yes
输入样例2:
{[}]
输出样例2:
no
正解:
#include<stdio.h>
#include<map>
#include<iostream>
#include<stack>
#include <algorithm>
using namespace std;
int main()
{
string s;
getline(cin,s);
int len=s.size();
map<char,char> m;
m['(']=')';
m['{']='}';
m['[']=']';
stack <char> a;
int flag=1;
for(int i=0;i<len;i++)
{
if(s[i]=='(' || s[i]=='{' || s[i]=='[')
a.push(s[i]);
else if(s[i]==')' || s[i]=='}' || s[i]==']')
{
if(a.size() && m[a.top()]==s[i])
a.pop();
else
{
flag=0;
break;
}
}
}
if(flag && a.size() == 0)
printf("yes\n");
else
printf("no\n");
return 0;
}
另一种思路不知道为啥是错的,欢迎大神点评评论:
#include <iostream>
using namespace std;
#define OVERFLOW -2
#define OK 1
#define ERROR 0
typedef char ElemType;
typedef char SElemType;
typedef int Status;
typedef struct StackNode
{
ElemType data;
struct StackNode *next;
} StackNode,*LinkStack;
Status InitStack(LinkStack &S)
{
S=NULL;
return OK;
}
Status Push(LinkStack &S,SElemType e)
{
LinkStack p=new StackNode;
p->data=e;
p->next=S;
S=p;
return OK;
}
Status Pop(LinkStack &S,SElemType &e)
{
if(S==NULL)
return ERROR;
e=S->data;
LinkStack p=S;
S=S->next;
delete p;
return OK;
}
SElemType GetTop(LinkStack S)
{
if(S!=NULL)
return S->data;
}
bool StackEmpty(LinkStack S)
{
if(S==NULL)
return true;
else
return false;
}
void Matching()
{
LinkStack S;
InitStack(S);
Status flag=1;
char str[101];
scanf(" %s",str);
char *ch=str;
while(*ch!='\0'&&flag)
{
if(*ch=='(' || *ch==')' || *ch=='[' || *ch==']' || *ch=='{' || *ch=='}')
{
SElemType x;
switch(*ch)
{
case '(':
Push(S,*ch);
break;
case '[':
Push(S,*ch);
break;
case '{':
Push(S,*ch);
break;
case ')':
if(!StackEmpty(S)&&GetTop(S)=='(')
{
Pop(S,x);
}
else
{
flag=0;
}
break;
case ']':
if(!StackEmpty(S)&&GetTop(S)=='[')
Pop(S,x);
else
{
flag=0;
}
break;
case '}':
if(!StackEmpty(S)&&GetTop(S)=='{')
{
Pop(S,x);
}
else
{
flag=0;
}
break;
}
}
*ch++;
}
if(StackEmpty(S)&&flag)
{
printf("yes\n");
}
else
{
printf("n\n");
}
}
int main()
{
Matching();
return 0;
}