LeetCode 20: Effective parentheses Valid Parentheses

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

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

Valid string must meet:

  1. Left bracket must be closed by a closing parenthesis of the same type.
  2. Left parenthesis must be closed in the correct order.

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 the empty string can be considered a valid string.

Note that an empty string is also considered valid.

Example 1:

输入: "()"
输出: true

Example 2:

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

Example 3:

输入: "(]"
输出: false

Example 4:

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

Example 5:

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

Problem-solving ideas:

Very simple question, each character string onto the stack, simple judgment can be. Such as:

输入: "{[]}"
初始栈为空,'{' 入栈
下一个字符
栈顶元素 '{'与 '[' 不匹配,'[' 入栈
下一个字符
栈顶元素 '['与 ']' 匹配,'[' 出栈
下一个字符
栈顶元素 '{'与 '}' 匹配,'}' 出栈
结束,栈为空,返回 True

Determining whether the key is a character, the matching criteria are opposite brace characters are not the same characters. Switch can be used to determine three kinds of brackets character, or three if statements, and then, or you can use a hash table mapping brackets relationship.

Java:

class Solution {
    public boolean isValid(String s) {
        Stack<Character> stack = new Stack<>();//初始化栈
        for (char b : s.toCharArray()) {
            switch (b) {
                case '(': {
                    stack.push(')');
                    break;
                }
                case '{': {
                    stack.push('}');
                    break;
                }
                case '[': {
                    stack.push(']');
                    break;
                }
                default: {//不匹配的情况返回false
                    if (stack.isEmpty() || stack.pop() != b) {
                        return false;
                    }
                }
            }
        }
        return stack.isEmpty();//栈为空则证明全部匹配,返回true,否则返回false
    }
}

Python:

Note: python does not switch ... case ... statement by the official if the judge so that instead of ...

class Solution:
    def isValid(self, s: str) -> bool:
        stack = []
        for c in s:
            if c == '[':
                stack.append(']')
            elif c == '(':
                stack.append(')')
            elif c == '{':
                stack.append('}')
            elif len(stack) == 0 or stack.pop() != c:
                return False
        return len(stack) == 0

Welcome attention to micro-channel public number: Write Love Bug

Guess you like

Origin www.cnblogs.com/zhangzhe532/p/11287310.html