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;
        }
    }
  • 相关阅读:
    apue-ubuntu环境搭建
    visualgdb 调试arm
    CMake速记
    umask
    转换函数conversion function
    c++ hex string array 转换 串口常用
    tcp与串口透传(select)
    sqlite3数据库修复SQLite-database disk image is malformed
    container_of宏
    shell 入门学习
  • 原文地址:https://www.cnblogs.com/qionglouyuyu/p/5401681.html
Copyright © 2011-2022 走看看