LeetCode Valid Parentheses(020)解法总结

334 阅读1分钟

描述

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

思路

使用栈的数据结构,当遇到左括号时入栈,碰到匹配的右括号是出栈。

要注意栈空时的出栈溢出和不匹配的右括号的报错。

class Solution {
    public boolean isValid(String s) {
        LinkedList<Character> stack = new LinkedList<Character>();
        int len = s.length(), count = 0;
        //对字符串进行遍历
        while(count < len){
            if(s.charAt(count) == '('||s.charAt(count) == '['||s.charAt(count) == '{'){
                //左括号入栈
                stack.add(s.charAt(count));
            }else{
                //右括号出栈
                //当栈空/未匹配到时返回false,否则按规则匹配
                if(stack.size() == 0){
                    return false;
                }else if(s.charAt(count) == ')' && stack.getLast() == '('){
                    stack.removeLast(); 
                }else if(s.charAt(count) == ']' && stack.getLast() == '['){
                    stack.removeLast(); 
                }else if(s.charAt(count) == '}' && stack.getLast() == '{'){
                    stack.removeLast(); 
                }else{
                    return false;
                }
            }
            count++;
        }
        //遍历整个输入后栈空即为合法
        if(stack.size() == 0){
            return true;
        }else{
            return false;
        }
    }
}
Runtime: 1 ms, faster than 98.70% of Java online submissions for Valid Parentheses.
Memory Usage: 37.4 MB, less than 5.06% of Java online submissions for Valid Parentheses.

这里使用的是LinkedList作为存储结构,其实java中自带是stack结构的。