[关闭]
@xunuo 2017-01-18T13:08:49.000000Z 字数 1294 阅读 963

Parentheses Balance---栈

Time limit3000 ms

STL

来源:vjudge:B-B


Description

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.

Input

The file contains a positive integer n and a sequence of n strings of parentheses ‘()’ and ‘[]’, one string a line.

Output

A sequence of ‘Yes’ or ‘No’ on the output file.

Sample Input

3
([])
(([()])))
([()[]()])()

Sample Output

Yes
No
Yes

题意:

第一行输入一个数n,表示接下来有n行

输入包含'(' ')' '[' ']'的字符串,如果能够组成完整,则输出"Yes",否则输出"No",但是要注意,当输入换行时,要输出"Yes";
解题思路:

因为那天几天正在讲区间DP,正好有模板,然后就拿着模板改了一下就交,然后......毫无意外的TLE了!唉,,后来用栈做的,其实很简单有木有?zz!!!其实如果当时用栈的话,,你可能也写不出来@_@!!

完整代码:

  1. #include<stdio.h>
  2. #include<string.h>
  3. #include<stack>
  4. #include<algorithm>
  5. using namespace std;
  6. int main()
  7. {
  8. int n;
  9. scanf("%d",&n);
  10. getchar();
  11. while(n--)
  12. {
  13. stack<char>s;
  14. char a[130];
  15. int flag=1;
  16. gets(a);
  17. int l=strlen(a);
  18. if(strcmp(a,"\n")==0)///哈哈哈!你又学到一个小东西!!
  19. {
  20. flag=1;
  21. continue;
  22. }
  23. for(int i=0;i<l;i++)
  24. {
  25. if(a[i]=='('||a[i]=='[')
  26. s.push(a[i]);
  27. else if(a[i]==')')
  28. {
  29. if(!s.empty()&&s.top()=='(')
  30. s.pop();
  31. else
  32. {
  33. flag=0;
  34. break;
  35. }
  36. }
  37. else if(a[i]==']')
  38. {
  39. if(!s.empty()&&s.top()=='[')
  40. s.pop();
  41. else
  42. {
  43. flag=0;
  44. break;
  45. }
  46. }
  47. }
  48. if(flag==0||!s.empty())
  49. printf("No\n");
  50. else
  51. printf("Yes\n");
  52. }
  53. return 0;
  54. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注