【LeetCode】20. Valid Parentheses

Difficulty:easy

 More:【目錄】LeetCode Java實現html

Description

https://leetcode.com/problems/valid-parentheses/java

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

An input string is valid if:post

  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.ui

Example 1:spa

Input: "()"
Output: true

Example 2:code

Input: "()[]{}"
Output: true

Example 3:htm

Input: "(]"
Output: false

Example 4:blog

Input: "([)]"
Output: false

Example 5:ip

Input: "{[]}"
Output: true

Intuition

Using a stack.

 

Solution

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

  

Complexity

Time complexity : O(n)

Space complexity : O(n)

 

 More:【目錄】LeetCode Java實現

相關文章
相關標籤/搜索