合法括号
发布时间: 2018年4月2日 20:46 时间限制: 1000ms 内存限制: 128M
描述
给定字符串,只包含以下括号:'(', ')', '{', '}', '[' and ']' , 判断输入是否合法。
括号匹配必按照要求:"()" and "()[]{}", 而不是 "(]" and "([)]"
输入
输入包含多组测试数据,每组测试数据占一行,不超过80个字符的字符串。
输出
对于每组测试数据,如果合法,输出true,否则false,每组输出占一行。
样例输入1
()()
样例输出1
true
______________________________________________________________________________________________________
参照之前的函数规律代码,利用stack 但是会出现超时现象 应当是判断数据过多
#include<iostream>
#include<cstdio>
#include<stack>
#include<string.h>
using namespace std;
int main()
{
stack<char> s;
if(!s.empty())
s.pop();
char t[85];
while(cin>>t){
for(int i=0;i<strlen(t);i++){
if(t[i]=='['||t[i]=='{'|t[i]=='(')
s.push(t[i]);
if((s.top()=='['&&t[i]==']') ||(s.top()=='{'&&t[i]=='}' )||(s.top()=='('&&t[i]==')'))
s.pop();
}
if(s.empty())
cout<<"true"<<endl;
else
cout<<"false"<<endl;
if(!s.empty())
s.pop();
}
return 0;
}
标程:
#include<cstdio>
#include<stack>
#include<cstring>
#include<iostream>
using namespace std;
int main()
{
//freopen("data.in","r",stdin);
char str[100];
while(scanf("%s",str)!=EOF)
{
stack<char>s;
while(!s.empty())
s.pop();
int flag=0;
for(int i=0;i<strlen(str);i++)
{
if(str[i]=='('||str[i]=='{'||str[i]=='[')
s.push(str[i]);
else
{
if(s.empty()||(str[i]==')'&&s.top()!='(')||(str[i]==']'&&s.top()!='[')||(str[i]=='}'&&s.top()!='{'))
{
flag=1;
break;
}
else
s.pop();
}
}
if(!s.empty())//这种情况很容易漏掉,比如"(((((",这也是不合法的!
flag=1;
printf("%s\n",flag?"false":"true");
}
return 0;
}
我应该是忘掉了判断栈为空的时候的条件
并且最后这种情况还是要好好考虑的