zoukankan      html  css  js  c++  java
  • 括号配对问题

    1. 括号匹配的四种可能性:
    ①左右括号配对次序不对
    ②右括号多于左括号
    ③左括号多于右括号
    ④左右括号匹配正确

    2. 算法思想:
    1.顺序扫描算数表达式(表现为一个字符串),当遇到三种类型的左括号时候让该括号进栈;
    2.当扫描到某一种类型的右括号时,比較当前栈顶元素是否与之匹配,若匹配,退栈继续推断;
    3.若当前栈顶元素与当前扫描的括号不匹配,则左右括号配对次序不对,匹配失败,直接退出;
    4.若字符串当前为某种类型的右括号而堆栈已经空,则右括号多于左括号,匹配失败,直接退出;
    5.字符串循环扫描结束时,若堆栈非空(即堆栈尚有某种类型的左括号),则说明左括号多于右括号,匹配失败;

    6.正常结束则括号匹配正确。


    代码例如以下:

     
    #include<iostream>
    #include<string>
    #include<string.h>
    #include<algorithm>
    #include<cstdio>
    using namespace std;
    
    struct sStack
    {
    	char sign[10010];
    	int top;
    };
    
    void initstack(sStack &s)
    {
    	s.top = -1;
    }
    
    bool isemptystack(sStack &s)
    {
    	return s.top == -1 ? 1 : 0;
    }
    
    int pushstack(sStack &s, char c)
    {
    	s.sign[++s.top] = c;
    	return 1;
    }
    
    int popstack(sStack &s)
    {
    	if(isemptystack(s))
    		return 0;
    	s.top--;
    	return 1;
    }
    
    char topstack(sStack &s)
    {
    	if(isemptystack(s))
    		return 0;
    	return s.sign[s.top];
    }
    
    int main()
    {
    	int N, len, i;
    	bool flag;
    	char str[10010];
    	sStack s;
    	scanf("%d", &N);
    	while(N--)
    	{
    		flag = 1;
    		scanf("%s", str);
    		len = strlen(str);
    		initstack(s);
    		for(i = 0; i < len; ++i)
    		{
    			if(str[i] == '(' || str[i] == '[' || str[i] == '{')
    				pushstack(s, str[i]);
    			else if(str[i] == ')')
    			{
    				if(isemptystack(s) || topstack(s) != '(')	flag = 0;
    				else	popstack(s);
    			}
    			else if(str[i] == ']')
    			{
    				if(isemptystack(s) || topstack(s) != '[')	flag = 0;
    				else	popstack(s);
    			}
    			else if(str[i] == '}')
    			{
    				if(isemptystack(s) || topstack(s) != '{')	flag = 0;
    				else	popstack(s);
    			}
    		}
    		if(!isemptystack(s)) {flag = 0;}
    		if(flag)	printf("Yes
    ");
    		else	printf("No
    ");
    	}
    	return 0;
    }        


  • 相关阅读:
    redis发布订阅
    redis学习笔记(面试题)
    redis安全 (error) NOAUTH Authentication required
    HDU3001 Travelling —— 状压DP(三进制)
    POJ3616 Milking Time —— DP
    POJ3186 Treats for the Cows —— DP
    HDU1074 Doing Homework —— 状压DP
    POJ1661 Help Jimmy —— DP
    HDU1260 Tickets —— DP
    HDU1176 免费馅饼 —— DP
  • 原文地址:https://www.cnblogs.com/lcchuguo/p/4480434.html
Copyright © 2011-2022 走看看