More:【目錄】LeetCode Java實現html
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
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
Using a stack.
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(); }
Time complexity : O(n)
Space complexity : O(n)
More:【目錄】LeetCode Java實現