Leetcode: 20-valid brackets

20. Valid parentheses

Given a string that only includes'(',')','{','}','[',']', judge whether the string is valid.

A valid string must meet:

The left parenthesis must be closed with the same type of right parenthesis.
The opening parenthesis must be closed in the correct order.
Note that an empty string can be considered a valid string.

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

Problem-solving ideas

绕了一大圈弯路,也是做过的题,只记得可以用栈来做,但是想到了用其他方法:字符数组的每一位在这一位后面的+1,+3,+5位置处,如果没有找到一个括号和它匹配,则匹配失败。。。这个方法不好解决如果遇到多个右括号。

退而求其次用,又忘了用栈怎么做。。

网上查了一下思路:
思路很简单,实现也不难,就是将字符串的左括号字符入栈,然后比较下一个括号是否和栈顶元素能匹配,如果能匹配,就出栈,如果也是左括号但不能匹配,则再入栈,再次比较下一个字符...,如果遇到右括号不能和栈顶元素匹配,则返回false

Code

class Solution {
    
    
    public boolean isValid(String s) {
    
    
       char[] chars = s.toCharArray();
        Stack<Character> stack = new Stack<>();
        Map<Character,Character> maps = new HashMap<>();
        maps.put('(', ')');
        maps.put('[', ']');
        maps.put('{', '}');
		//将特殊情况排除掉
        if(s.equals("")){
    
    
            return true;
        }
        //将特殊情况排除掉
        if(chars[0] == '}' || chars[0] == ')' ||chars[0] == ']' ||
                chars[chars.length-1] == '(' || chars[chars.length-1] == '{' ||chars[chars.length-1] == '['){
    
    
            return false;
        }

        for (int i = 0; i < chars.length; i++) {
    
    
        //左括号都入栈
            if(chars[i] == '(' || chars[i] == '[' ||chars[i] == '{'){
    
    
                stack.push(chars[i]);
                continue;
            }
            //栈不为空并且栈顶元素 = 数组元素
            if(!stack.isEmpty() && maps.get(stack.peek()) == chars[i]){
    
    		//出栈
                stack.pop();
            }else{
    
    
                return false;
            }

        }
        //栈空则全部匹配
        if(stack.isEmpty()){
    
    
            return true;
        }else{
    
    
            return false;
        }

    }
}

test

Insert picture description here
Insert picture description here

Guess you like

Origin blog.csdn.net/JAYU_37/article/details/107238739