roblem Description
给你一串字符,不超过50个字符,可能包括括号、数字、字母、标点符号、空格,你的任务是检查这一串字符中的( ) ,[ ],{ }是否匹配。
Input
输入数据有多组,处理到文件结束。
Output
如果匹配就输出“yes”,不匹配输出“no”
Sample Input
sin(20+10)
{[}]
Sample Output
yes
no
解决方案:遇到左括号,直接进栈,其他字符直接省略,
遇到右括号,如果栈顶元素正好匹配,则使栈顶出栈,其他的直接跳出循环。
注意点:一开始的时候卡了,一直WA,没搞清楚cin和gets的用法,以后要注意。
使用cin时,>> 是会过滤掉不可见的字符(如 空格 回车,TAB 等),
cin>>noskipws>>input[j];//不想略过空白字符,那就使用 noskipws 流控制
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
# define maxSize 100
typedef char elem;
typedef struct node
{
elem *top,*base;
int stackSize;
}_sta;
void Init(_sta &s)
{
s.base = (elem *)malloc(maxSize *sizeof(elem));
if(!s.base) exit(-1);
else s.top = s.base;
s.stackSize = maxSize;
}
void push(_sta &s,elem k)
{
if(s.top - s.base >= s.stackSize){
s.base = (elem *)realloc(s.base,(maxSize + 10)*sizeof(elem));
if(!s.base) exit(-1); //分配失败
s.stackSize += 10;
}
*s.top++ = k;
}
elem pop(_sta &s)
{
elem k;
if(s.top == s.base) return 0;
k = *(--s.top);
return k;
}
elem top(_sta &s)
{
elem k;
if(s.top == s.base) return 0;
k = *(s.top - 1);
return k;
}
bool IsEmpty(_sta &s)
{
if(s.base == s.top) return true;
else return false;
}
int main()
{
char str[110];
//while(cin>>str){ //这里不能用cin,会省略空格
while(gets(str)){
_sta l;
Init(l);
int i;
int len = strlen(str);
for(i=0;i<len;i++){
if(str[i] == '('||str[i] == '['||str[i] == '{'){
push(l,str[i]);
}
else if(str[i] == ')'||str[i] == ']'||str[i] == '}'){
if(IsEmpty(l)) break;
else {
if((top(l) == '('&&str[i] == ')')||(top(l) == '['&&str[i] == ']')||(top(l) == '{'&&str[i] == '}')){
pop(l);
}
else break;
}
}
}
if(IsEmpty(l)&&i == len) cout<<"yes"<<endl;
else cout<<"no"<<endl;
}
return 0;
}