zoukankan      html  css  js  c++  java
  • 20. Valid Parentheses (Stack)

    Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

    The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.

    struct Stack{
        struct StackNode* top;
        int size;
    };
    
    struct StackNode{
        char value;
        struct StackNode* next;
    };
    
    bool isEmpty(struct Stack* s){
        if(s->size==0) return true;  
        else return false;
    }
    
    void push(struct Stack* s, char value){
        struct StackNode* node = malloc(sizeof(struct StackNode));
        node->value = value;
        node->next = s->top;
        s->top = node;
        s->size++;
    }
    
    char pop(struct Stack* s){
        struct StackNode* node = s->top;
        char value = node->value;
        s->top = node->next;
        free(node);
        s->size--;
        return value;
    }
    
    bool isValid(char* s) {
        struct Stack* charStack = malloc(sizeof(struct Stack));
        charStack->top = NULL;
        charStack->size = 0;
      
        while(*s!=''){
            if(*s == ')'){
                if(isEmpty(charStack) || pop(charStack)!='(') return false;
            }
            else if(*s == ']'){
                if(isEmpty(charStack) || pop(charStack)!='[') return false;
            }
            else if(*s == '}'){
                if(isEmpty(charStack) || pop(charStack)!='{') return false;
            }
            else{
                push(charStack,*s);
            }
            s++;
        }
        
        if(isEmpty(charStack)) {
            free(charStack);
            return true;
        }
        else{
            free(charStack);
            return false;
        }
    }
  • 相关阅读:
    C++11线程池
    muduo的事件处理(Reactor模型关键结构)
    sed和awk
    gdb
    C#访问级别
    C#表达式树浅析
    C#并发实战Parallel.ForEach使用
    c#获取本月有哪些周六、周日
    重装了Devexpress后项目报Dll引用找不到问题解决办法
    C#单例模式
  • 原文地址:https://www.cnblogs.com/qionglouyuyu/p/5401681.html
Copyright © 2011-2022 走看看