【数据结构】栈的应用——检测括号是否匹配

1.括号匹配的检验

假设表达式中允许包含三种括号:圆括号、方括号和大括号,其嵌套的顺序随意,即{()[ ] }或[ { ()} ]等为正确的格式,即匹配成功,[ ( ] )或( ( ) }等为不正确的格式,即不匹配。检验括号是否匹配的方法可用“期待的紧迫程度”这个概念来描述。

括号匹配分下面几种情况:

char a[] = "(())abc{[(])}" ; // 左右括号次序匹配不正确
char b[] = "(()))abc{[]}" ; // 右括号多于左括号 
char c[] = "(()()abc{[]}" ; // 左括号多于右括号 
char d[] = "(())abc{[]()}" ; // 左右括号匹配正确

2.代码实现

代码如下:

#include 
#include 
using namespace std;

bool MatchBrackets(char str[], size_t size)
{
    stack<char> s;
    for (size_t i = 0; i < size; ++i)
    {
        if (str[i] != '(' && str[i] != ')' &&
            str[i] != '[' && str[i] != ']' &&
            str[i] != '{' && str[i] != '}')
        {
            continue;
        }
        else
        { 
            if ('(' == str[i] || '{' == str[i] || '[' == str[i])
            {
                s.push(str[i]);
            }
            else
            {
                if (s.empty())
                {
                    cout << "右括号比左括号多" << endl;
                    return false;
                }
                char c = s.top();
                if (('(' == c && ')' == str[i]) ||
                    ('{' == c && '}' == str[i]) ||
                    ('[' == c && ']' == str[i]))
                {
                    s.pop();
                }
                else
                {
                    cout << "括号次序不匹配" << endl;
                    return false;
                }
            }
        }
    }
    if (!s.empty())
    {           
        cout << "左括号比右括号多" << endl;
        return false;
    }
    cout << "正确匹配" << endl;
    return true;
}

int main()
{
    char a[] = "(())abc{[(])}";  // 左右括号次序匹配不正确
    char b[] = "(()))abc{[]}";   // 右括号多于左括号
    char c[] = "(()()abc{[]}";   // 左括号多于右括号
    char d[] = "(())abc{[]()}";  // 左右括号匹配正确

    cout << MatchBrackets(a, strlen(a)) << endl;
    cout << MatchBrackets(b, strlen(b)) << endl;
    cout << MatchBrackets(c, strlen(c)) << endl;
    cout << MatchBrackets(d, strlen(d)) << endl;
    return 0;
}

你可能感兴趣的:(数据结构)