LeetCode Valid Parentheses(020)解法總結

NewCoder1024發表於2020-03-31

描述

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結構的。


相關文章