合法的括号匹配

来源:互联网 发布:ipad不能用淘宝怎么办 编辑:程序博客网 时间:2024/05/01 00:10

20. Valid Parenthese



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.

Subscribe to see which companies asked this question

题目大概就是这三种括号的匹配,主要的利用Stack的先进后出的原理来进行匹配,看代码应该一下就明白了

typedef struct stack {    char c;    struct stack   *next;} Stack;void create(Stack **ptop){    *ptop = NULL;}void push(Stack **ptop, char c){    Stack   *tmp;        tmp = malloc(sizeof *tmp);    tmp->c = c;    tmp->next = *ptop;        *ptop = tmp;}void pop(Stack **ptop, char *c){    Stack   *tmp;        if (! *ptop) return;        tmp = *ptop;    *c = tmp->c;    *ptop = (*ptop)->next;    free(tmp);}int empty(Stack **ptop){   return *ptop == NULL; }bool isValid(char* s) {    Stack   *ss;    char    c;        create(&ss);    while (*s) {        switch (*s) {        case '(':        case '[':        case '{':            push(&ss, *s);            break;        case ')':        case ']':        case '}':            if (empty(&ss)) return 0;            pop(&ss, &c);            if (c + 1 != *s                && c + 2 != *s) return 0;            break;        default:            break;        }        ++s;    }        if (!empty(&ss)) return 0;    return 1;}



0 0
原创粉丝点击