【数据结构--栈的应用--括号匹配】

括号匹配

前言

括号匹配问题是较为经典的栈的应用了,在Leetcode和数据结构书中时常出现

例如

给定一个字符串,其包含( , ) ,{ , } , [ , ]以及数字,要求判断其括号是否匹配,即:

  • 左括号必须用相同类型的右括号闭合
  • 左括号必须以正确的顺序闭合

实例 1:

输入: "[2 + (1 - 3)] * 4"
输出:1

实例 2:

输入:"(  )    )"
输出:0

算法思想

  • 当遇到 ‘(’ ,’[’ ,’{’ 时进行压栈操作,将其压入栈中
  • 当遇到 ‘)’ ,’]’, ‘}’ 时进行弹栈操作,若此时弹出的元素和此时遇到的括号匹配,则继续进行,否则直接退出(即不匹配)
  • 为了防止出现单独的 ‘)’ ,’]’ 或 ‘}’ 导致判断错误,在栈的栈底添加了 ‘#’ 标识符,若匹配结束而最后弹出的不是 ‘#’ 则表示有多余单独的 ‘)’ ,’]’ 或 ‘}’ ,则直接退出(即也不匹配)

栈的定义及其操作

typedef struct CharStack
{
    int top;    /* 用于栈顶指针 */
    int data[MAXSIZE];
} *CharStackPtr,CharStack;

//输出栈
void outPutStack(CharStackPtr tempStack)
{
    for(int i = 0; i <= tempStack->top; ++i)
    {
        printf("%c ",tempStack->data[i]);
    }
    printf("\n");
}

//初始化栈
CharStackPtr CharStackInit()
{
    CharStackPtr resultPtr = (CharStackPtr)malloc(sizeof(CharStack));
    resultPtr->top = -1;
    return resultPtr;
}

//压栈
void push(CharStackPtr tempStackPtr, char tempValue)
{
    if(tempStackPtr->top >= MAXSIZE - 1)
    {
        printf("无法压入元素%c:堆栈已满!\n",tempValue);
        return ;
    }
    tempStackPtr->top ++;
    tempStackPtr->data[tempStackPtr->top] = tempValue;
}

//弹栈
char pop(CharStackPtr tempStackPtr)
{
    if (tempStackPtr->top == -1)
    {
        printf("不能弹出元素:堆栈为空!\n");
        return NULL;
    }
    tempStackPtr->top --;
    return tempStackPtr->data[tempStackPtr->top+1];
}

括号匹配核心代码

//括号匹配
bool parenthesisMatching(char* tempString)
{
    /* 在栈底部压入'#'并初始化堆栈。 */
    CharStackPtr tempStack = CharStackInit();
    push(tempStack,'#');
    char tempChar,tempPopedChar;
    for(int i = 0; i< strlen(tempString); ++i)
    {
        tempChar = tempString[i];
        switch (tempChar)
        {
        case '(':
        case '[':
        case '{':
            push(tempStack,tempChar);
            break;
        case ')':
            tempPopedChar = pop(tempStack);
            if(tempPopedChar != '(')
            {
                return false;
            }
            break;
        case ']':
            tempPopedChar = pop(tempStack);
            if(tempPopedChar != '[')
            {
                return false;
            }
            break;
        case '}':
            tempPopedChar = pop(tempStack);
            if(tempPopedChar != '{')
            {
                return false;
            }
            break;
        default:
            break;
        }
    }
    tempPopedChar = pop(tempStack);
    if(tempPopedChar != '#')
    {
        return false;
    }
    return true;
}

完整代码

#include <stdio.h>
#include <string.h>
#include <malloc.h>

#define MAXSIZE 10

typedef struct CharStack
{
    int top;    /* 用于栈顶指针 */
    int data[MAXSIZE];
} *CharStackPtr,CharStack;

//输出栈
void outPutStack(CharStackPtr tempStack)
{
    for(int i = 0; i <= tempStack->top; ++i)
    {
        printf("%c ",tempStack->data[i]);
    }
    printf("\n");
}

//初始化栈
CharStackPtr CharStackInit()
{
    CharStackPtr resultPtr = (CharStackPtr)malloc(sizeof(CharStack));
    resultPtr->top = -1;
    return resultPtr;
}

//压栈
void push(CharStackPtr tempStackPtr, char tempValue)
{
    if(tempStackPtr->top >= MAXSIZE - 1)
    {
        printf("无法压入元素%c:堆栈已满!\n",tempValue);
        return ;
    }
    tempStackPtr->top ++;
    tempStackPtr->data[tempStackPtr->top] = tempValue;
}

//弹栈
char pop(CharStackPtr tempStackPtr)
{
    if (tempStackPtr->top == -1)
    {
        printf("不能弹出元素:堆栈为空!\n");
        return NULL;
    }
    tempStackPtr->top --;
    return tempStackPtr->data[tempStackPtr->top+1];
}

//括号匹配
bool parenthesisMatching(char* tempString)
{
    /* 在栈底部压入'#'并初始化堆栈。 */
    CharStackPtr tempStack = CharStackInit();
    push(tempStack,'#');
    char tempChar,tempPopedChar;
    for(int i = 0; i< strlen(tempString); ++i)
    {
        tempChar = tempString[i];
        switch (tempChar)
        {
        case '(':
        case '[':
        case '{':
            push(tempStack,tempChar);
            break;
        case ')':
            tempPopedChar = pop(tempStack);
            if(tempPopedChar != '(')
            {
                return false;
            }
            break;
        case ']':
            tempPopedChar = pop(tempStack);
            if(tempPopedChar != '[')
            {
                return false;
            }
            break;
        case '}':
            tempPopedChar = pop(tempStack);
            if(tempPopedChar != '{')
            {
                return false;
            }
            break;
        default:
            break;
        }
    }
    tempPopedChar = pop(tempStack);
    if(tempPopedChar != '#')
    {
        return false;
    }
    return true;
}

//测试
void parenthesisMatchingTest()
{
    char *tempExpression;
    tempExpression = "[2 + (1 - 3)] * 4";
    bool tempMatch = parenthesisMatching(tempExpression);
    printf("表达式%s括号匹配吗?  %d\n",tempExpression,tempMatch);

    tempExpression = "(  )    )";
    tempMatch = parenthesisMatching(tempExpression);
    printf("表达式%s括号匹配吗?  %d\n",tempExpression,tempMatch);

    tempExpression = "()()(())";
    tempMatch = parenthesisMatching(tempExpression);
    printf("表达式%s括号匹配吗?  %d\n",tempExpression,tempMatch);
    
    tempExpression = "({}[])";
    tempMatch = parenthesisMatching(tempExpression);
    printf("表达式%s括号匹配吗?  %d\n",tempExpression,tempMatch);

    tempExpression = ")(";
    tempMatch = parenthesisMatching(tempExpression);
    printf("表达式%s括号匹配吗?  %d\n",tempExpression,tempMatch);
}

int main()
{
    parenthesisMatchingTest();
}

运行测试

表达式[2 + (1 - 3)] * 4括号匹配吗?  1
表达式(  )    )括号匹配吗?  0
表达式()()(())括号匹配吗?  1
表达式({}[])括号匹配吗?  1
表达式)(括号匹配吗?  0
  • 9
    点赞
  • 49
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

黎子想写好代码

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值