@xunuo
2017-01-18T21:08:49.000000Z
字数 1294
阅读 1048
Time limit3000 ms
STL
来源:vjudge:B-B
You are given a string consisting of parentheses () and []. A string of this type is said to be correct:
(a) if it is the empty string
(b) if A and B are correct, AB is correct,
(c) if A is correct, (A) and [A] is correct.
Write a program that takes a sequence of strings of this type and check their correctness. Your program can assume that the maximum string length is 128.
The file contains a positive integer n and a sequence of n strings of parentheses ‘()’ and ‘[]’, one string a line.
A sequence of ‘Yes’ or ‘No’ on the output file.
3
([])
(([()])))
([()[]()])()
Yes
No
Yes
题意:
第一行输入一个数n,表示接下来有n行
输入包含'(' ')' '[' ']'的字符串,如果能够组成完整,则输出"Yes",否则输出"No",但是要注意,当输入换行时,要输出"Yes";
解题思路:
因为那天几天正在讲区间DP,正好有模板,然后就拿着模板改了一下就交,然后......毫无意外的TLE了!唉,,后来用栈做的,其实很简单有木有?zz!!!其实如果当时用栈的话,,你可能也写不出来@_@!!
完整代码:
#include<stdio.h>
#include<string.h>
#include<stack>
#include<algorithm>
using namespace std;
int main()
{
int n;
scanf("%d",&n);
getchar();
while(n--)
{
stack<char>s;
char a[130];
int flag=1;
gets(a);
int l=strlen(a);
if(strcmp(a,"\n")==0)///哈哈哈!你又学到一个小东西!!
{
flag=1;
continue;
}
for(int i=0;i<l;i++)
{
if(a[i]=='('||a[i]=='[')
s.push(a[i]);
else if(a[i]==')')
{
if(!s.empty()&&s.top()=='(')
s.pop();
else
{
flag=0;
break;
}
}
else if(a[i]==']')
{
if(!s.empty()&&s.top()=='[')
s.pop();
else
{
flag=0;
break;
}
}
}
if(flag==0||!s.empty())
printf("No\n");
else
printf("Yes\n");
}
return 0;
}