标签:
题目:
You are given a string consisting of parentheses () and []. A string of this type is said to be 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
题意:
给出一个由括号()和[]组成的字符串。下例类型的字符串是正确的:
(1)
如果它是空字符串
(b)
如果A和B是正确的,AB是正确的,
(c)
如果是A正确的,(A)和[A]是正确的。
思路:
先输入一个数组并且创建一个栈,后遍历数组中的字符,如果是‘(‘或‘[‘时就入栈,如果等于栈顶就将栈顶的字符删除;
最后判断栈是否为空,为空输出Yes,否则为No。
注意当数组为/n是输出Yes。
相关知识:
栈提供了如下的操作
1 #include<iostream> 2 #include<stack> 3 #include<cstdio> 4 #include<cstring> 5 using namespace std; 6 int main() 7 { 8 int t,i; 9 char b[150]; 10 cin>>t; 11 getchar(); 12 while(t--) 13 { 14 stack<char>a; 15 gets(b); 16 if(strcmp(b,"/n")==0) 17 {cout<<"Yes"<<endl; 18 continue; 19 } 20 for(i=0;b[i];) 21 {if(a.empty()) 22 a.push(b[i]); 23 else if((a.top()==‘(‘&&b[i]==‘)‘)||(a.top()==‘[‘&&b[i]==‘]‘)) 24 a.pop(); 25 else 26 if(b[i]==‘(‘||b[i]==‘[‘) 27 a.push(b[i]); 28 i++; 29 } 30 if(a.empty()) 31 cout<<"Yes"<<endl; 32 else cout<<"No"<<endl; 33 } 34 return 0; 35 }
标签:
原文地址:http://www.cnblogs.com/fenhong/p/4667617.html