Valid Parentheses 合法的括号匹配

来源:互联网 发布:淘宝代购延长收货 编辑:程序博客网 时间:2024/05/16 09:38

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.

题目大意:给定一个字符串只包含“(){}[]”,判断该字符串的括号是否匹配

思路:利用栈的思想,不匹配入栈,匹配出栈,最后查看栈顶

#include <string.h>bool isValid(char* s) {    int len = strlen(s);    char *p = malloc(len);    int top = 0;    //从下标1开始存储        if(!p)        return false;    memset(p, 0x0, len);    while(*s)    {        //查看assic码,得知匹配情况的assic码差值        if(*s - p[top] == 1 || *s - p[top] == 2)        {            p[top] = 0;            top--;        }        else        {            top++;            p[top] = *s;        }        s++;    }    free(p);    return (top ? false : true);}


0 0
原创粉丝点击