Given a string s
containing just the characters '('
, ')'
, '{'
, '}'
, '['
and ']'
, determine if the input string is valid.
An input string is valid if:
This is a classic problem that can be elegantly solved using a stack data structure.
{ ')': '(', '}': '{', ']': '[' }
.s
.
(
, {
, [
), push it onto the stack.)
, }
, ]
), check the stack. If the stack is empty or if the top element of the stack is not the corresponding opening bracket, the string is invalid. If it matches, pop the stack.The time complexity is O(n) because we process each character once. The space complexity is O(n) in the worst case (a string of all opening brackets).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22