2020-10-07

    科技2024-08-03  28

    C++数据结构

    判断字符串中括号是否匹配

    #include using namespace std; #include<string.h>

    class Stack{ public: Stack(); void Push(char x); void Pop(); char Gettop(); void Empty(); private: char data[50]; int top; };

    Stack::Stack() { top = -1; }

    void Stack::Push(char x) { top++; data[top] = x; }

    void Stack::Pop() { top–; }

    char Stack::Gettop() { if (top == -1) { return 0; } else { return data[top]; } }

    void Stack::Empty() { if (top == -1) { cout << “yes”; } else { cout << “no”; } }

    int main() { Stack S; char x[30]; int length,flag = 0; cin >> x; length = strlen(x); for (int i = 0; i < length; i++) { if (x[i] == ‘)’) { if (S.Gettop() == ‘(’) { S.Pop(); } else { flag = 1; break; } } else if (x[i] == ‘]’) { if (S.Gettop() == ‘[’) { S.Pop(); } else { flag = 1; break; } } else if(x[i] == ‘}’) { if (S.Gettop() == ‘{’) { S.Pop(); } else { flag = 1; break; } } else { S.Push(x[i]); } } if (flag == 1) { cout << “no”; } else { S.Empty(); } }

    Processed: 0.010, SQL: 8