Uva 673 - Parentheses Balance
Parentheses Balance |
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
Miguel Revilla
2000-08-14
#include<stdio.h> #include<string.h> int main() { char pipei[130], temp[130]; int i, front, rear, len, n, flag; scanf("%d", &n); getchar(); while(n--) { memset(pipei, '\0', sizeof(pipei)); memset(temp, '\0', sizeof(temp)); rear = front = 0; fgets(temp, 130, stdin); len = strlen(temp); if(temp[len-1] == '\n') len--; flag = 0; for(i=0; i<len; ++i) { if(temp[i] == ' ') continue; if(temp[i] == '(' || temp[i] == '[') pipei[rear++] = temp[i]; else { if(temp[i] == ')') { if(rear > 0 && pipei[--rear] == '(') { pipei[rear] = '\0'; } else {flag = 1; break;} } else { if(rear > 0 && pipei[--rear] == '[') { pipei[rear] = '\0'; } else {flag = 1; break;} } } } if(flag || rear != front) printf("No\n"); else printf("Yes\n"); } return 0; }
解题报告:
括号匹配,很早之前做过的,没想到这次做竟然会WA,其中一个原因是没有考虑到只输入一个回车的问题,还有就是思维不够严谨,中间判断的时候出了篓子。
![物役记](https://s2.ax1x.com/2019/05/26/VE5YD0.jpg)
更多内容请关注个人微信公众号 物役记 (微信号:materialchains)
作者:雪影蓝枫
本文版权归作者和博客园共有,欢迎转载,未经作者同意须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。