3 [(]) (]) ([[]()])
No No Yes
1 #include<stdio.h> 2 #include<string.h> 3 int main() 4 { 5 int k,top; 6 int N,i,l; 7 char s1[10005],s2[10005]; 8 scanf("%d",&N); 9 getchar(); 10 while(N--) 11 { 12 gets(s1); 13 l=strlen(s1); 14 if(l%2==1) 15 printf("No"); 16 else 17 { 18 top=1; 19 s2[top]=s1[0]; 20 for(i=1;i<l;i++) 21 {//判断 s1 是否匹配 逐一进行匹配 实行:先进的后匹配原则 如果匹配则将其弹出 否则压入s2中 22 if((s1[i]==‘)‘ && s2[top]==‘(‘) || (s1[i]==‘]‘&&s2[top]==‘[‘)) 23 top--;//弹出栈顶 24 else 25 s2[++top]=s1[i];//元素压入 26 } 27 if(top==0) printf("Yes"); 28 else printf("No"); 29 } 30 printf("\n"); 31 } 32 return 0; 33 }
数组来模拟栈的思想 先进后出原则 先进的后匹配 逐一进行与栈顶进行匹配 匹配的弹出栈顶 不匹配的压入栈 最后判断栈是否为空即栈顶是否为0即为全部匹配
1 /* 2 #include<cstring> 3 #include<stack> 4 #include<iostream> 5 #include<algorithm> 6 using namespace std; 7 int main() 8 { 9 int n, i; 10 cin >> n; 11 while(n--) 12 { 13 char str[10005]; 14 stack<char> s; 15 while(!s.empty()) s.pop(); 16 cin >> str; 17 int len = strlen(str); 18 if(len % 2 == 1) 19 cout << "No" << endl; 20 else 21 { 22 s.push(str[0]); 23 for(i = 1; i < len; i++) 24 { 25 if((str[i] == ‘)‘ && s.top() == ‘(‘) || (str[i] == ‘]‘ && s.top() == ‘[‘)) 26 s.pop(); 27 else 28 s.push(str[i]); 29 } 30 if(!s.empty()) 31 cout << "No" << endl; 32 else 33 cout << "Yes" << endl; 34 } 35 } 36 return 0; 37 }*/
直接调用系统栈
原文:http://www.cnblogs.com/xiaoyunoo/p/3516188.html