[Problem]
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.
[Analysis]
思路上属于利用data structure的特性。利用Stack FIFO的特性可以大大简化这道题。
[Solution]
import java.util.Stack; public class Solution { public boolean isValid(String s) { Stack<Character> stack = new Stack<>(); for (int i = 0; i< s.length(); i++) { char c = s.charAt(i); if (c == '(') { stack.push(')'); } else if (c == '[') { stack.push(']'); } else if(c == '{') { stack.push('}'); } else { if (stack.size() == 0 || c != stack.pop()) { return false; } } } return stack.empty(); } }