UVA—673 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
题意:判断括号的匹配,主要用到STL的栈

   

#include<iostream>
#include<stack>
#include<stdio.h>
#include<string>
using namespace std;
int main()
{
    int n,istrue;
    while(cin>>n)
    {
        getchar();               //!!!!!!!!!
        while(n--)
        {
            istrue=1;
            stack<int> q;
            string a;
            getline(cin,a);           //getline()可以输入包括空格在内的所有字符,以回车为结束符  cin 和scanf 遇到空格会停止读取!!
            for(int i=0;i<a.size();i++)
            {
                if(a[i]=='('||a[i]=='[')
                    q.push(a[i]);
                else if(a[i]==' ')
                    continue;
                else if(!q.empty()&&q.top()=='('&&a[i]==')')
                {
                    q.pop();
                    continue;
                }
                else if(!q.empty()&&q.top()=='['&&a[i]==']')
                {
                    q.pop();
                    continue;
                }
                else
                {
                istrue=0;
                break;
                }
            }
        if(istrue&&q.empty())
            cout<<"Yes"<<endl;
        else
            cout<<"No"<<endl;
         while(!q.empty())
            q.pop();
        }
    }
}
getline() 函数实际上有三个参数,第三个参数指定字符串的结束符,也就是当 getline() 函数遇到这个字符时,就不再接受输入了。例如
getline(cin, str, 's');  
即使输入的是 abcsdef ,读入到 str 的内容却只有 abc ,因为遇到字符 ‘s’ 时,getline() 便停止读入了。
即输入 abcsabc 按回车键后,程序以 enter 作为输入完成的信号,getline()  函数开始读入缓冲区的内容,它将结束符 ‘s’ 前的部分读入到变量 str ,舍弃结束符 's' 及其后面的部分。



猜你喜欢

转载自blog.csdn.net/asd1637579311/article/details/79990943