您的位置:首页 > 其它

UVA673 Parentheses Balance【堆栈+输入流】

2018-01-29 18:51 423 查看
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. Yourprogram can assume that the maximum string length is 128.InputThe file contains a positive integer n and a sequence of n strings of parentheses ‘()’
and ‘[]’, one stringa line.OutputA sequence of ‘Yes’ or ‘No’ on the output file.

Sample Input

3

([])

(([()])))

([()[]()])()

Sample Output

Yes

No

Yes

问题链接:UVA673
Parentheses Balance

#include <iostream>
#include <stack>
using namespace std;

int main()
{
int n;
char c;
scanf("%d", &n);
getchar();
while(n--) {
stack<char> s; //定义在循环里面每次都清零

while((c = getchar()) != '\n') {
if(s.empty()) //如果是空,堆栈;
s.push(c);
else {
if((s.top() == '(' && c == ')') || (s.top() == '[' && c == ']'))
s.pop(); //如果有匹配的则弹栈;
else
s.push(c); //否则压栈
}
}

printf("%s\n", s.empty() ? "Yes" : "No");
}

return 0;
}
下面附加c语言程序有助于理解

#include <stdio.h>

#define N 128

char stack
;
int ps;

int main(void)
{
int n;
char c;

scanf("%d", &n);
getchar();
while(n--) {
ps = 0;
while((c = getchar()) != '\n') {
if(ps > 0) {
if((stack[ps - 1] == '(' && c == ')') || (stack[ps - 1] == '[' && c == ']'))
ps--;
else
stack[ps++] = c;
} else
stack[ps++] = c;
}

printf("%s\n", (ps > 0) ? "No" : "Yes");
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: