• 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;
    
    }
    
  • 相关阅读:
    模拟实现链表
    模拟实现内存操作函数
    实现一个简单的进度条
    简单的通讯录(C语言实现)
    sizeof和strlen
    动态联编
    不用第三个变量交换两个变量的值
    内存对齐
    字符串指针和字符数组的区别
    vs中的一些bug解决
  • 原文地址:https://www.cnblogs.com/xl1164191281/p/4668703.html
Copyright © 2020-2023  润新知