您的位置:首页 > 其它

20.Valid Parentheses 栈的应用:括号匹配

2017-09-23 21:06 501 查看
十分简单的括号匹配,用栈来操作就可以了

#define max_size 1000001

class Solution {

public:

    typedef struct SqStack{

            int top;

            char data[max_size];

        }Stack;

    void Init_Stack(Stack &s)

        {

            s.top = -1;

        }

        

        int PopStack(Stack &s,char &c)

        {

            if(s.top==-1)

                return 0;

            c = s.data[s.top--];

            return 1;

        }

        

        int PushStack(Stack &s,char c)

        {

            if(s.top==max_size)

                return 0;

            s.data[++s.top] = c;

            return 1;

        }

    

    bool isValid(string s) {

        

    Stack st;

    Init_Stack(st);

    int i=0;

    char c;

    while(s[i]!='\0')

    {

        if(s[i]=='('|| s[i] =='{' ||s[i]=='[')

            PushStack(st,s[i]);

        else{

        if(s[i]==')')

        {

            PopStack(st,c);

            if(c!='(')

                return false;

        }

        if(s[i]==']')

        {

            PopStack(st,c);

            if(c!='[')

                return false;

        }

        if(s[i]=='}')

        {

            PopStack(st,c);

            if(c!='{')

                return false;

        }

        }

        i++;

    }

    if(st.top==-1)

        return true;

    return false;   

    }

};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: