括号匹配 (栈和队列)

题目描述:

假设一个算术表达式中可以包含三种括号:圆括号“(”和“)”,方括号“[”和“]”和花括号“{”和“ ”,且这三种括号可按任意的次序嵌套使用(如:…[…{… …[…]…]…[…]…(…)…)。编写判别给定表达式中所含括号是否正确配对出现的算法。输出结果YES 或者 NO。

输入

5+{[2X5]+2}

输出

YES

样例输入

8-[{2+7]}

样例输出

NO

解题思路:利用栈的基本知识

代码如下:

#include<iostream>

#include<stdio.h>

#include<string.h>

#include<algorithm>

#include<stack>

#include<stdlib.h>

#include<math.h>

#define inf 1e6+5

using namespace std;

typedef long long ll;

void FindStack(char arr[])

{

    stack<char>st;

    int flag=1;

    int num=strlen(arr);

    for(int i=0; i<num; i++)   //  具体括号匹配操作

    {

        switch(arr[i])

        {

        case '(':

            st.push(arr[i]);

            break;

        case '[':

            st.push(arr[i]);

            break;

        case '{':

            st.push(arr[i]);

            break;

        case ')':

            if(st.top()=='(')st.pop();

            else flag=0;

            break;

        case ']':

            if(st.top()=='[')st.pop();

            else flag=0;

            break;

        case '}':

            if(st.top()=='{')st.pop();

            else flag=0;

            break;

        }

    }

    if(!flag)

        cout<<"NO"<<endl;

    else

    {

        if(!st.empty())

            cout<<"NO"<<endl;

        else

            cout<<"YES"<<endl;

    }

    return ;

}

int main()

{

    char arr[1000];

    scanf("%s",&arr);

    FindStack(arr);

    return 0;

}

发布了44 篇原创文章 · 获赞 7 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/DreamTrue1101/article/details/83654226