LeetCode 有效的括号

Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

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

由于只包含字符的字符串'('')''{''}''['']',确定输入字符串是有效的。

如果输入字符串有效:

  1. 必须使用相同类型的括号关闭左括号。

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

请注意,空字符串也被视为有效。

思路

1.将问题简化成一种括号(()())

在任意一个位置上,左括号的数量 >= 右括号的数量

在最后一个位置上,左括号的数量 == 右括号的数量

程序中只需要标记左括号的数量与右括号的数量即可;

思维方式:

【互反操作】左右括号抵消,

当出现左括号就加1【“(”等价于进入】;

出现右括号就减1【“)”等价于出去】;

【一对括号等价于事件的解决】;

2.升级为多个括号的时候,只需要判断是否匹配即可。

​ 每次匹配成功出栈,判断最后栈是否为空即可。

3.在这里用数组模拟栈的操作,每次匹配成功指针回移,

如果遇到‘(’,‘[’ ,'{',就将其压入数组中,top++;


bool isValid(char* s) {
    char stack[10000000];
    int len = 0;
    int top = -1;
    while(s[len]){
        if(s[len] == ')'){
            if(top >= 0 && stack[top] == '(')  top--;
            else return false;
        }else if(s[len] == ']'){
            if(top >= 0 && stack[top] == '[')   top--;
            else return false;
        }else if(s[len] == '}'){
            if(top >= 0 && stack[top] == '{')   top--;
            else return false;
        }else{
            top++;
            stack[top] = s[len];          
        }
        len++;
    }
    return top == -1;
    
}

 

你可能感兴趣的:(数据结构,LeedCode)