Given a string s
containing just the characters '('
, ')'
, '{'
, '}'
, '['
and ']'
, determine if the input string is valid.
An input string is valid if:
- Open brackets must be closed by the same type of brackets.
- Open brackets must be closed in the correct order.
- Every close bracket has a corresponding open bracket of the same type.
Example 1:
Input: s = "()"
Output: true
Example 2:
Input: s = "(]" Output: false
SOLUTION:
class Solution: def isValid(self, s: str) -> bool: dicts: dict={'(':')', '{':'}', '[':']'} stack: List[str] = [] for i in s: if i in dicts.keys(): stack.append(i) if i in dicts.values(): if not stack or dicts[stack.pop()] !=i:#key != value return False return not stack #true if stack is empty
- Time complexity:
- Space complexity:
Create a dictionary,
dicts
, where the opening brackets are keys and the corresponding closing brackets are values.Initialize an empty stack,
stack
, to keep track of the opening brackets encountered.Iterate through each character,
i
, in the input string,s
.If
i
is an opening bracket (found indicts.keys()
), push it onto the stack usingstack.append(i)
.If
i
is a closing bracket (found indicts.values()
), check if the stack is empty or the top of the stack (stack.pop()
) does not match the current closing bracket (dicts[stack.pop()] != i
). If either of these conditions is true, returnFalse
as the brackets are not balanced.After processing all characters in
s
, check if the stack is empty. If it is empty, returnTrue
as the brackets are balanced. Otherwise, returnFalse
.
Comments
Post a Comment