[LeetCode] 20. Valid Parentheses
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.
Thought process:
Iterate through the string:
- If the character is an opening parenthesis, push it onto a stack.
- If the character is a closing parenthesis, compare it with the parenthesis on top of the stack:
- If they match, pop the top parenthesis off.
- If they don't match, return false.
Return if the stack is empty at the end of loop.
Solution:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | class Solution { public boolean isValid(String s) { Stack<Character> stack = new Stack<>(); for (char c : s.toCharArray()) { if (c == '(' || c == '[' || c == '{') { stack.push(c); } else if (stack.isEmpty()) { return false; } else if (c == ')' && stack.pop() != '(') { return false; } else if (c == ']' && stack.pop() != '[') { return false; } else if (c == '}' && stack.pop() != '{') { return false; } } return stack.isEmpty(); } } |
Time complexity: O(n).
Comments
Post a Comment