UVA - Parentheses Balance(栈)
发布日期:2021-07-01 00:16:14 浏览次数:2 分类:技术文章

本文共 1395 字,大约阅读时间需要 4 分钟。

题目链接:

Time limit: 3.000 seconds

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

Problem solving report:

Description: 给你由'[',']','(',')'组成的字符串,问能否进行括号匹配。

Problem solving: 利用栈的性质,只要遇到能匹配的就移出栈,否则就进栈,最后再判断一下栈是否为空就行了。

#include 
#include
#include
using namespace std;int main(){ int t; char str[130]; scanf("%d%*c", &t); while (t--) { gets(str); stack
s; for (int i = 0; str[i]; i++) { if (!s.empty()) { if ((s.top() != '[' || str[i] != ']') && (s.top() != '(' || str[i] != ')')) s.push(str[i]); else s.pop(); } else s.push(str[i]); } if (!s.empty()) printf("No\n"); else printf("Yes\n"); } return 0;}

 

转载地址:https://lzyws739307453.blog.csdn.net/article/details/86665075 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:UVA - Tree Recovery(二叉树)
下一篇:POJ - Frogs' Neighborhood(Havel-Hakimi)

发表评论

最新留言

留言是一种美德,欢迎回访!
[***.207.175.100]2024年04月14日 16时54分40秒