基於棧的表達式中多種括號匹配算法

題目

假設表達式中允許包含3種括號:圓括號、方括號和大括號。設計一個算法採用順序棧判斷表達式中的括號是否正確匹配。

解題

基本思路如下:實例化一個字符棧,維持一個bool變量flag,初始化爲true。然後遍歷整個表達式:

  1. 如果是三種正括號‘(’   '['   '{',則入棧;

  2. 如果是三種反括號‘)’   ']'   '}',則對比棧頂元素,如果是正好對應的正括號,則將其從棧中彈出,否則flag設爲false,break停止循環;

  3. 如果是其他字符,跳過;

  4. 最後判斷,如果flag爲true且棧爲空,則括號正確匹配,否則不正確匹配。

代碼如下:

// 目前我在複習C++,暫時對泛型編程那一塊不太熟悉了,所以先定義另外的字符棧,下次再用模板吧。
// StackForChar.h 字符棧

#include <iostream>
using namespace std;

class StackForChar
{
private:
    int maxSize;
    int top;
    char * ptr;
public:
    StackForChar(const int maxSize_)
    {
        maxSize = maxSize_;
        top = -1;
        ptr = new char[maxSize_];
    }

    ~StackForChar()
    {
        delete [] ptr;
    }

    bool Push(const char item)
    {
        if (maxSize == top + 1)
        {
            cout << "The Stack is already full!" << endl;
            return false;
        }
        ptr[++top] = item;
        return true;
    }

    bool Pop(char & item)
    {
        if (top == -1)
        {
            cout << "The Stack is already empty!" << endl;
            return false;
        }
        item = ptr[top--];
        return true;
    }

    bool isEmpty()
    {
        if (top == -1) return true;
        return false;
    }
};
// Verification.h 驗證函數
#include <iostream>
#include "StackForChar.h"
#include <string.h>
using namespace std;

void Verification(string expression)
{
    StackForChar stack = 100;
    char chr = 0;
    bool flag = true;
    for (int i = 0; i < expression.length(); i++)
    {
        chr = 0;
        if (expression[i] == '(' || expression[i] == '[' || expression[i] == '{')
        {
            stack.Push(expression[i]);
        }
        else if (expression[i] == ')')
        {
            stack.Pop(chr);
            if (chr != '(')
            {
                flag = false;
                break;
            }
        }
        else if (expression[i] == ']')
        {
            stack.Pop(chr);
            if (chr != '[')
            {
                flag = false;
                break;
            }
        }
        else if (expression[i] == '}')
        {
            stack.Pop(chr);
            if (chr != '{')
            {
                flag = false;
                break;
            }
        }
    }
    if (flag && stack.isEmpty()) cout << "All right!" << endl;
    else cout << "Error!!!" << endl;
}
// main.cpp 主函數

#include <iostream>
#include "Transform.h"
#include <stdio.h>
#include "Verification.h"
using namespace std;

int main()
{
    char *str = new char[20];
    string expression;
    cout << "Please input the expression:" << endl;
    cin >> str;
    expression = str;
    delete [] str;
    Verification(expression);
    getchar();
    getchar();
    return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章