zoukankan      html  css  js  c++  java
  • Problem A 栈

    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
    分析:
    这个括号配对问题很符合后进先出-栈的方法,遇到左括号时进栈,遇到右括号时将栈顶元素与之配对的括号出栈。

    #include <iostream>
    #include <stack>
    using namespace std;
    int main()
    {
    	int n;
    	cin >> n;
    	cin.get();
    	while (n--)
    	{
    		stack<char>st_ch;
    		int loge = 1;
    		char c;
    		while (cin.get(c) && c != '
    ')
    		{
    			if (c == ')')
    			{
    				if (st_ch.empty())
    					loge = 0;
    				else if (st_ch.top() == '(')
    					st_ch.pop();
    				else
    					loge = 0;
    			}
    			else if (c == ']')
    			{
    				if (st_ch.empty())
    					loge = 0;
    				else if (st_ch.top() == '[')
    					st_ch.pop();
    				else
    					loge = 0;
    			}
    			else
    				st_ch.push(c);
    		}
    		if (st_ch.empty()&&loge)
    			cout << "Yes" << endl;
    		else
    			cout << "No" << endl;
    
    	}
    	return 0;
    
    }
    
  • 相关阅读:
    Educational Codeforces Round 58
    Educational Codeforces Round 59
    Codeforces Round #534 (Div. 2)
    Codeforces Round #531 (Div. 3)
    Codeforces Round #536 (Div. 2)
    Codeforces Round #530 (Div. 2)
    Codeforces Round #533 (Div. 2)
    Codeforces Round #535 (Div. 3)
    Codeforces Round #532 (Div. 2)
    Codeforces Round #538 (Div. 2)
  • 原文地址:https://www.cnblogs.com/xl1164191281/p/4668703.html
Copyright © 2011-2022 走看看