zoukankan      html  css  js  c++  java
  • Balancing Symbols

    symbols匹配问题

    #include<iostream>
    #include<string>
    using namespace std;
    
    struct Node
    {
    	char data;
    	Node*next;
    };
    
    struct LinkStack
    {
    	Node*top;
    };
    
    LinkStack*create()
    {
    	LinkStack*stack = new LinkStack;
    	stack->top = NULL;
    	return stack;
    }
    
    bool isEmpty(LinkStack*stack)
    {
    	return (stack->top == NULL);
    }
    
    void pop(LinkStack*stack)
    {
    	Node*p = stack->top;
    	stack->top = stack->top->next;
    	delete p;
    }
    
    void push(LinkStack*stack, char item)
    {
    	Node*p = new Node;
    	p->data = item;
    	p->next = stack->top;
    	stack->top = p;
    }
    
    char Top(LinkStack*stack)
    {
    	return stack->top->data;
    }
    
    int main()
    {
    	int n;
    	cin >> n;
    	while (n-->0)
    	{
    		string s;
    		cin >> s;
    		LinkStack*stack = create();
    		bool flag = true;
    		int n = s.size();
    
    		for (int i = 0; i < n; i++)
    		{
    			if (s[i] == '(' || s[i] == '[' || s[i] == '{')
    				push(stack, s[i]);
    			if (s[i] == ')')
    			{
    				if (!isEmpty(stack))
    				{
    					if (isEmpty(stack) && Top(stack) != '(')
    					{
    						flag = false;
    						break;
    					}
    					else
    					{
    						pop(stack);
    					}
    				}
    				else
    				{
    					flag = false;
    					break;
    				}
    			}
    			else if (s[i] == ']')
    			{
    				if (!isEmpty(stack))
    				{
    					if (Top(stack) != '[')
    					{
    						flag = false;
    						break;
    					}
    					else
    					{
    						pop(stack);
    					}
    				}
    				else
    				{
    					flag = false;
    					break;
    				}
    			}
    			else if (s[i] == '}')
    			{
    				if (!isEmpty(stack))
    				{
    					if (Top(stack) != '{')
    					{
    						flag = false;
    						break;
    					}
    					else
    					{
    						pop(stack);
    					}
    				}
    				else
    				{
    					flag = false;
    					break;
    				}
    			}
    		}
    		if (!isEmpty(stack))
    			flag = false;
    		if (flag)
    			cout << "Yes" << endl;
    		if (!flag)
    			cout << "No" << endl;
    
    		delete stack;
    	}
    	return 0;
    }
    

      

  • 相关阅读:
    winform 关于Messagebox自动定时关闭
    Git常用命令
    使用消息队列异步化系统
    在Servlet(或者Filter,或者Listener)中使用spring的IOC容器
    基于Annotation与SpringAOP的缓存简单解决方案
    Ant自动构建
    Quartz定时调度
    Sybase数据库的分页功能
    oracle 日期相减
    n个List<Map>合并,Map中某属性值相等的value值相加
  • 原文地址:https://www.cnblogs.com/KennyRom/p/5911105.html
Copyright © 2011-2022 走看看