20. 有效的括号

给定一个只包括 '('')''{''}''['']' 的字符串,判断字符串是否有效。

有效字符串需满足:

1.左括号必须用相同类型的右括号闭合。

2.左括号必须以正确的顺序闭合。

注意空字符串可被认为是有效字符串。

示例 1:

输入: "()"
输出: true

示例 2:

输入: "()[]{}"
输出: true

示例 3:

输入: "(]"
输出: false

示例 4:

输入: "([)]"
输出: false

示例 5:

输入: "{[]}"
输出: true

解题答案

bool isValid(char * s){
    if(s==NULL||s[0]=='\0'){
        return true;
    }
    int length=strlen(s);
    char *stack=(char *)malloc(sizeof(char)*(length));
    int top=0;
    for(int count=0;count<length;count++)
    {
        if(s[count]=='('||s[count]=='{'||s[count]=='['){
            stack[top++]=s[count];
        }
        else{
            if((--top)<0) return false;
            if(s[count]==')'&&stack[top]!='(') return false;
            if(s[count]=='}'&&stack[top]!='{') return false;
            if(s[count]==']'&&stack[top]!='[') return false;
        }
    }

    return (!top);
}

  

posted @ 2020-05-31 11:27  leagueandlegends  阅读(81)  评论(0编辑  收藏  举报