题目描述
计算机系的同学从大一就开始学习程序设计语言了。初学者总是容易写出括号不匹配的程序。至今你仍然清楚地记得,那天上机的时候你的程序编译出错,虽然你使尽了吃奶的力气也没有把错误逮着。你实在没有办法只得举手向老师请教。结果老师走过来一看,板着脸,指着屏幕,很不高兴地冲着你说:“括号!括号!括号没有匹配!”自那以后,你痛定思痛决定写一个程序,帮助分析程序的括号是否出错,以免再出洋相。为了简化工作,你假定程序的注释、字符常量、字符串常量中都不包含括号,同时你只检查()[]{}这三种括号。
输入
输入为多组数据,最后一组数据以@结束,其余每组数据以#结束。@与#不会出现在正常程序中。每个程序含有不超过255个括号字符,程序长度不确定。
输出
每组数据输出一行,如果括号匹配无误则输出"Wonderful",括号匹配出现问题则输出"Be Careful"(请注意大小写和拼写错误,这些问题都将导致Wrong Answer)。 你只要关心括号是否匹配,不需要在意其余的语法错误。
样例输入
int main() { return 0; } # int main() { @
样例输出
Wonderful Be Careful#include<iostream> #include <stack> using namespace std; char a[3000000]; int main() { stack<char> k; int i; while(cin.getline(a,3000000)) { for(i=0;a[i]!='\0'&&a[0]!='#'&&a[0]!='@';i++) { if (!k.empty()&&((k.top()-a[i]==-2)||(k.top()-a[i]==-1))) { k.pop(); } else if(a[i]==40||a[i]==41||a[i]==91||a[i]==93||a[i]==123||a[i]==125) { k.push(a[i]); } } if(a[0]=='@') { if(k.empty()) { cout << "Wonderful" << endl; } else { cout << "Be Careful" << endl; } break; } if (a[0]=='#') { if(k.empty()) { cout << "Wonderful" << endl; } else { cout << "Be Careful" << endl; } while (!k.empty()) { k.pop(); } } } return 0; }
最近学了栈,就想用一下数组而不用STL来实现。
<pre name="code" class="cpp">#include <iostream> using namespace std; int main() { char a[1010],b[1010]; int t,i,len; cin >> t ; cin.get(); while (t--) { len=-1; cin.getline(a,1010); for(i=0;a[i]!='\0';++i) { if(len!=-1&&((b[len]-a[i]==-2)||(b[len]-a[i]==-1))) /*一开始总是没法实现进出栈,看了看原来的代码后, 发现原来没判断首次是否为空就直接压栈了,所以一直错。*/ { len--; } else { b[++len]=a[i] ; } } if (len==-1) { cout << "Yes" << endl; } else { cout << "No" << endl; } } return 0; }
总结:凡是实现进栈的操作时都要判断是否为空栈。
另外在uva上做过一道差不多的题,也是挺坑人的,还要判断是否为没输入数据的情况。。。
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
#include <iostream> using namespace std; int main() { int n,i,k; char str[200]; char cnt[200]; cin >> n; cin.get(); while (n--) { k=-1; cin.getline(str,200); for (i=0;str[i]!='\0'&&str[0]!='\n';++i) { if (k!=-1&&(cnt[k]-str[i]==-1||cnt[k]-str[i]==-2)) { k--; } else { cnt[++k]=str[i]; } } if(k!=-1) cout << "No" << endl; else cout << "Yes" << endl; } return 0; }