码迷,mamicode.com
首页 > 其他好文 > 详细

括号配对问题——解题心得

时间:2015-07-20 23:19:30      阅读:171      评论:0      收藏:0      [点我收藏+]

标签:

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

解题思路:

注意:

1、匹配的括号序列长度必然为偶数

2、第一个括号必须为左括号(‘(‘ 或 ‘[‘ )

3、括号不会交叉嵌套出现(如:([)] 就不符合),具有对称性。

4、一行若是“\n“字符串也输出"Yes"。

如果我们当前看到了一个左括号,则我们不能判断其与哪个括号匹配,因为与之匹配的括号必定在其后面,因此我们还需要向后搜索。但是当我们看到一个右括号的时候,我们必然可以判断其与前面哪个括号匹配(或者找不到匹配)。因此我们的第一个匹配是从后面第一个右括号开始的,当我们找到一对匹配的括号的时 候,我们就可以把这对括号消除,然后继续找下一个右括号,继续消除,直到算法结束。显然我们遇到的第一个右括号必定与其前一个括号匹配,否则不满足第三条 规则。当我们删除了第一个匹配的括号之后,剩下的括号形成了一个新的序列。于是可以应用上面的思路继续经行匹配。

特征:后面的括号先被删除,最前面的括号最后被删除。这个规则符合栈的后进先出的规则。

程序代码:

 #include <iostream>
  #include <cstdio>
  #include <stack>
  #include <cstring>
  using namespace std;
  char str[200];

  bool judge(char x,char y)
  {
      if (x==[&&y==])   return 1;
    if (x==(&&y==))   return 1;
    return 0;
  }

  bool left(char x)
  {
      if( x==[||x==()   return 1;
      return 0;
  }
  int main()
  {
      int t;cin>>t;
      getchar();
      while(t--)
      {
          stack<char>s;
          gets(str);
           if(strcmp(str,"\n")==0)    {cout<<"Yes"<<endl;continue;}
         for(int i=0;i<strlen(str);i++)
          {
             if(s.empty())      //判断栈是否为空
                s.push(str[i]);
             else
                if (!judge(s.top(),str[i]))
             {
                 if(left(str[i]))
                    s.push(str[i]);
             }
             else s.pop();

          }
          if(s.empty()) cout<<"Yes"<<endl;
          else cout<<"No"<<endl;
      }
      return 0;
  }

 

括号配对问题——解题心得

标签:

原文地址:http://www.cnblogs.com/www-cnxcy-com/p/4662740.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!