[20]. Effective parentheses

Valid parenthesis

 


topic

Includes only a given (, ), {, }, [, ]string, determines whether the string is valid.

A valid string must meet:

  1. The left bracket must be closed with the same type of right bracket.
  2. The left bracket must be closed in the correct order.

Note that an empty string can be considered a valid string.

Example 1:

输入: "()"
输出: true

Example 2:

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

Example 3:

输入: "(]"
输出: false

Example 4:

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

Example 5:

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

 


Function prototype

C function prototype:

bool isValid(char * s){}

 


Boundary judgment

bool isValid(char * s){
    if( s == NULL || *s == '\0' )
        return true;
}

 


Algorithm design: stack

Ideas: If you have the left half of the brackets (such as (, , [) {on the stack, the right half of the face brackets (such as ), , ]) }and the top of the stack elements can match (is a pair of parentheses), then the stack, repeated this Process ... In the end, the empty stack is valid parentheses. If there are still parentheses on the stack, it means that there is no perfect match.

bool isValid(char * s){
	if( s == NULL || *s == '\0' )     // 题目说:空字符串可被认为是有效字符串。
        return true;
        
    int len = strlen(s);
    if ( !len ) return true;
    
    char stack[len];
    int top = -1;
    for (int i = 0; i < len; ++i) {
        if (top > -1 && ((stack[top] == '(' && s[i] == ')') || (stack[top] == '[' && s[i] == ']') || (stack[top] == '{' && s[i] == '}'))) {
            top--;
        } else {
            stack[++top] = s[i];
        }
    }

    return top == -1 ? true:false;
}

 


Published 133 original articles · Like 378 · Visits 70,000+

Guess you like

Origin blog.csdn.net/qq_41739364/article/details/105496589