括号匹配检测(难度:半颗星)

来源:互联网 发布:第一会软件 编辑:程序博客网 时间:2024/06/10 19:10

问题描述:

输入一个字符串,字符串中只包含两种字符:’(‘和’)’,判断字符串的括号是否匹配,如果匹配输出YES,否则输出NO。

例如:
(())是匹配的
()))是不匹配的

参考代码:

#define _CRT_SECURE_NO_WARNINGS#include <stdio.h>#include <string.h>#include <stack>std::stack<char>st;int main(){    char str[500];    int i;    scanf("%s", str);    for (i = 0; i < (int)strlen(str); i++)    {        if (str[i] == '(')            st.push(str[i]);        else        {            if (st.empty())            {                printf("NO\n");                return 0;            }            st.pop();        }    }    if (st.empty())        printf("YES\n");    return 0;}

运行结果:

这里写图片描述

原创粉丝点击