Valid Parentheses

An input string is valid if:

1. Open brackets must be closed by the same type of brackets.
2. Open brackets must be closed in the correct order.

Note that an empty string is also considered valid.

Example 1:

Input: “()”
Output: true

Example 2:

Input: “()[]{}”
Output: true

Example 3:

Input: “(]”
Output: false

Example 4:

Input: “([)]”
Output: false

Example 5:

Input: “{[]}”
Output: true

bool isValid(char s[]) {
    //定义一个栈
    char sign[10000];
    int top = 0;
    
    int i = 0;
    while(s[i] != '\0'){
        if(s[i] == '(' || s[i] == '{' || s[i] == '[' )
            sign[++top] = s[i];
        else if(s[i] == ')' && sign[top] == '(' && top > 0)
            top--;
        else if(s[i] == '}' && sign[top] == '{' && top > 0)
            top--;
        else if(s[i] == ']' && sign[top] == '[' && top > 0)
            top--;
        else
            return false;
        i++;
    }
    if(top == 0)
        return true;
    else
        return false;
}

发布者

Avatar photo

常轩

总要做点什么吧!

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注