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

来源:互联网 发布:android chroot linux 编辑:程序博客网 时间:2024/06/01 08:34

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

#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;   
    }
};
阅读全文
0 0
原创粉丝点击