LeetCode(49)-Valid Parentheses

时间:2022-03-13 12:04:23

题目:

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

The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.

思路:

  • 题意:一个字符串,只是包含括号,判断括号是不是合法的使用
  • 这个问题的思路是使用栈,这一类对应的问题都是使用栈,遇到前括号压栈,遇到后括含出栈,是不是对应,看最后是不是为0
  • -

代码:

public class Solution {
    public boolean isValid(String s) {
        Stack<Character> stack = new Stack<Character>();
        for(int i = 0;i < s.length();i++){
            char a = s.charAt(i);
            if(a == '('||a == '{'||a == '['){
                stack.push(a);
            }else if(a == ')' && !stack.isEmpty() && stack.peek() == '('){
                stack.pop();
            }else if(a == '}' && !stack.isEmpty() && stack.peek() == '{'){
                stack.pop();
            }else if(a == ']' && !stack.isEmpty() && stack.peek() == '['){
                stack.pop();
            }else{
                return false;
            }
        }
        return stack.isEmpty();
    }
}