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!='\0'){
        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;
    }
}

 

posted on 2016-04-17 18:05  joannae  阅读(209)  评论(0编辑  收藏  举报

导航