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

十分简单的括号匹配,用栈来操作就可以了

#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;   
    }
};

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