2015 HUAS Summer Training#2 A

题目:

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.

题目大意:找到()或[]这样的集合  并判断是否全是这样的集合。

解题思路:for循环一个一个去找例如:

 1 for(i=0;i<p;i++) 
 2         {
 3             for(j=i+1;j<p;j++)
 4             {
 5                 if(s[i]=='('||s[i]=='[')
 6                 {
 7                     if(s[i]=='('&&s[j]==')'||s[i]=='['&&s[j]==']')
 8                     {
 9                         if((j-i)%2!=0)
10                         {
11                             s[i]=0;
12                             s[j]=0;
13                             l++;
14                             break;
15                         }
16                     }
17                 }
18             }
19         }

代码:

 1 #include<iostream>
 2 #include<string>
 3 #include <cstring>
 4 #include<vector>
 5 using namespace std;
 6 const int maxn=128+5;
 7 int main()
 8 {
 9     int n,i,j,p;
10     char s[maxn];
11     cin>>n;
12     getchar();
13     while(n--)
14     {
15         int l=0;
16         gets(s); 
17         p=strlen(s);
18         if(strcmp(s,"
")==0)
19         {
20             cout<<"Yes"<<endl;
21             continue;
22         }        
23         for(i=0;i<p;i++) 
24         {
25             for(j=i+1;j<p;j++)
26             {
27                 if(s[i]=='('||s[i]=='[')
28                 {
29                     if(s[i]=='('&&s[j]==')'||s[i]=='['&&s[j]==']')
30                     {
31                         if((j-i)%2!=0)
32                         {
33                             s[i]=0;
34                             s[j]=0;
35                             l++;
36                             break;
37                         }
38                     }
39                 }
40             }
41         }
42         if(l*2==p)
43             cout<<"Yes"<<endl;
44         else cout<<"No"<<endl;    
45     }
46     return 0;
47 }
原文地址:https://www.cnblogs.com/huaxiangdehenji/p/4674289.html