One written test question per day--leetCode:20. Valid parentheses (simple)

One written test a day –leetCode:20. Valid parentheses (simple)

##leetCode:20. Valid parentheses (simple)

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

A valid string must meet:

  1. The left parenthesis must be closed with the same type of right parenthesis.
  2. The opening parenthesis 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

Solution one: stack

Judging the validity of parentheses can be solved by using the data structure "stack".

We traverse the given string s , and when we encounter an opening parenthesis, we expect that in the subsequent traversal, a closing parenthesis of the same type will close it. Since the left parenthesis encountered later must be closed first , we can put this left parenthesis on the top of the stack.

When we encounter a closing parenthesis, we need to close an opening parenthesis of the same type. At this point, we can take out the left parenthesis at the top of the stack and determine whether they are the same type of parenthesis. If it is not the same type, or there is no left parenthesis in the stack, then the string s is invalid and False is returned . In order to quickly determine the type of parentheses, we can use HashMap to store each type of parentheses. The key of the hash map is the right parenthesis, and the value is the same type of left parenthesis.

After the traversal is over, if there is no left parenthesis in the stack, it means that we close all the left parentheses in the string s and return True , otherwise return False .

Note that the length of a valid string must be an even number, so if the length of the string is an odd number, we can directly return False to save the subsequent traversal judgment process.

   public boolean isValid(String s) {
    
    
              //获取字符串的长度
        int n = s.length();
        //如果字符串长度为奇数,则不可能有效,直接返回false
        if (n % 2==1) {
    
    
            return false;
        }

        //用哈希映射(HashMap)存储每一种括号。
        HashMap<Character, Character> pairs = new HashMap(){
    
    
            {
    
    
                put(')','(');
                put(']','[');
                put('}','{');
            }
        };

        //创建一个队列
        Deque<Character> stack=new LinkedList<>();

        for (int i = 0; i <n ; i++) {
    
    
            char c = s.charAt(i);
            if (pairs.containsKey(c)) {
    
    
                if (stack.isEmpty() || stack.peek() != pairs.get(c)) {
    
    
                    return false;
                }
            stack.pop();
            }else {
    
    
                stack.push(c);
            }
        }

        return stack.isEmpty();
    }

Insert picture description here

Solution two:

    public boolean isValid(String s) {
    
    
        LinkedList<Character> stack = new LinkedList<>();
        for (char c : s.toCharArray()) {
    
    
            if (c == '[') stack.push(']');
            else if (c == '(') stack.push(')');
            else if (c == '{') stack.push('}');
            else if (stack.isEmpty() || c != stack.pop()) return false;
        }
        return stack.isEmpty();
    }

Insert picture description here

Guess you like

Origin blog.csdn.net/qq_37924905/article/details/108586446