您的位置:首页 > 其它

LeetCode 20 Valid Parentheses(括号匹配)

2017-03-28 11:54 501 查看
[LeetCode 20]

Description

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.

bool isValid(char* s) {

    int top=0;

    int i=1;

    int length = strlen(s);

    char stack[length];

    if(length == 0 | length == 1)  return 0;

    for(i=0;i<strlen(s);i++){

        if(top == 0){

            stack[0] = s[i];

            top ++;

            continue;

        }

        switch(stack[top - 1]){

            case '(':

            if( s[i] == '{' || s[i] == '[' || s[i] == '(' ){

                stack[top]=s[i];

                top ++;

            }

            else if(s[i] == ')')  top--;

            else return 0;

            break;

             

            case '[':

            if( s[i] == '{' || s[i] == '[' || s[i] == '(' ){

                stack[top]=s[i];

                top ++;

            }

            else if(s[i] == ']')  top--;

            else return 0;

            break;

             

            case '{':

            if( s[i] == '{' || s[i] == '[' || s[i] == '(' ){

                stack[top]=s[i];

                top ++;

            }

            else if(s[i] == '}')  top--;

            else return 0;

            break;

        }

    }

    if(!top) return 1;

    else return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息