括号匹配问题

     [[(( ))]](())[[[]]]

编写程序看上述括号是否匹配。

看到上述问题,我们应该首先考虑到用栈来解决。

栈的特点:先进后出。

代码实现如下:

#include <iostream>
#include <stack>
#include <stdio.h>
#include <string.h>
using namespace std;



#define S 10000

bool fun(char *arr)
{
    stack <char>stk;
    char *p = arr;
    while(*p)
    {
        //如果是左括号,则入栈  进入下一次循环
        if(*p == '(' || *p == '[')
        {
            stk.push(*p);
            p++;
            continue;
        }
        //如果是右括号   首先判断栈是否为空  如果不为空 再判断栈顶元素是否和×p匹配
        if(*p == ')' && !stk.empty()&& stk.top() == '(')
        {
            stk.pop();
            p++;
            continue;
        }else if(*p == ')' && !stk.empty()&& stk.top() != '(')
        {
            return false;           //如果不匹配直接返回 false
        }
        if(*p == ']' && !stk.empty()&& stk.top() == '[')
        {
            stk.pop();
            p++;
            continue;
        }else{
            return false;
        }
    }
    //循环结束  如果栈为空  返回true
    if(stk.empty())
        return true;
    return false;
}

  下面是给出的主函数 来测试我们写出的算法

int main()
{
    int input_num;
    int i;
    char arr[S] = "";
    cin >> input_num;
    for(i=0;i<input_num;i++)
    {
        memset(arr,0,sizeof(arr));
        scanf("%s",arr);
        if(fun(arr))
        {
            cout << "Yes" <<endl;
        }else{
            cout << "No" <<endl;
        }
    }
}

  

原文地址:https://www.cnblogs.com/wzqstudy/p/9979786.html