Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.code
The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.input
Time Complexity
O(n)
Space Complexity
O(n)string
Traverse the string, if it is "([{" , push into stack, if it is ")}]", check if the stack is empty first, if it is empty, return invalid. If it is not empty, check if the stack.pop() match ")}]".it
public boolean isValid(String s) { //corner case if(s == null || s.length() < 2) return false; Stack<Character> stack = new Stack<Character>(); for(int i = 0; i < s.length(); i++){ char c = s.charAt(i); if(c == '(' || c == '{' || c == '['){ stack.push(c); }else{ if(stack.isEmpty()) return false; if(c == ')'){ if(!stack.isEmpty() && stack.pop() != '(') return false; }else if(c == '}'){ if(!stack.isEmpty() && stack.pop() != '{') return false; }else if(c == ']'){ if(!stack.isEmpty() && stack.pop() != '[') return false; } } } return stack.isEmpty(); }
[])
){
()[]{}
(]
([)]im