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.
给你一个由圆括号( )和[组成的字符串。这种类型的字符串被认为是正确的: ( A )如果是空字符串,( B )如果A和B是正确的,AB是正确的,( c )如果A是正确的,( A )和[ A ]是正确的。编写一个程序,接受这种类型的字符串序列,并检查它们的正确性。您的程序可以假设最大字符串长度为128。输入文件包含一个正整数n和一系列n个圆括号' ( ) '和' [ ',一行一个字符串。在输出文件上输出一系列“是”或“否”。
题意即为:输入括号()或[ ], 判断输入的括号们 是否 规范 成对 相对应。
Sample Input
3
([])
(([()])))
([()[]()])()
Sample Output
Yes
No
Yes
#include<iostream>
#include<cstdio>
#include<cstring>
#include<vector>
#include<algorithm>
#include<stack>
using namespace std;
int main()
{
int n;
scanf("%d",&n); //三个例子;
getchar();
while(n--)
{
int flag=1;
char k;
stack<char>s; //定义字符型栈s;
while((k=getchar())!='\n') //当k不为回车,即还未到最后一个;
{
//如果k为括号 ( 或 [ ,元素k入栈;
if(k=='('||k=='[')
s.push(k);
//如果k为括号 ) 或 ] ;
if(k==')'||k==']')
{
//如果栈中已空,即没有与之对应的,则记flag为零
if(s.empty())
flag=0;
//如果栈中不为空,并且栈的顶部与此括号对应,则弹出栈顶元素;
else if((s.top()=='('&&k==')')||(s.top()=='['&&k==']'))
s.pop();
}
}
//当flag为1,说明没有出现过不对应情况,并且栈中已全部对应完,则输出YES;
if(flag==1&&s.empty())
printf("Yes\n");
else
printf("No\n");
}
return 0;
}