Easy
Given a string s
containing just the characters '('
, ')'
, '{'
, '}'
, '['
and ']'
, determine if the input string is valid.
An input string is valid if:
Example 1:
Input: s = “()”
Output: true
Example 2:
Input: s = “()[]{}”
Output: true
Example 3:
Input: s = “(]”
Output: false
Example 4:
Input: s = “([)]”
Output: false
Example 5:
Input: s = “{[]}”
Output: true
Constraints:
1 <= s.length <= 104
s
consists of parentheses only '()[]{}'
.%% Check if binary has valid parentheses
-spec is_valid(S :: unicode:unicode_binary()) -> boolean().
is_valid(S) ->
process_binary(S, []).
%% Process binary with stack, where empty list is empty stack
-spec process_binary(binary(), list()) -> boolean().
process_binary(<<>>, []) ->
true;
process_binary(<<>>, _Stack) ->
false;
process_binary(<<Char/utf8, Rest/binary>>, Stack) ->
case Char of
40 -> process_binary(Rest, [40 | Stack]); % '('
91 -> process_binary(Rest, [91 | Stack]); % '['
123 -> process_binary(Rest, [123 | Stack]); % '{'
41 -> % ')'
case Stack of
[40 | NewStack] -> process_binary(Rest, NewStack);
_ -> false
end;
93 -> % ']'
case Stack of
[91 | NewStack] -> process_binary(Rest, NewStack);
_ -> false
end;
125 -> % '}'
case Stack of
[123 | NewStack] -> process_binary(Rest, NewStack);
_ -> false
end;
_ -> false % Invalid character
end.