You are given a string that contains only the following characters: '(', ')', '{', '}', '[' and ']'. Your task is to determine whether the input string is valid. The validation rules are as follows:
Here are some examples:
Your function should take a string s
as input and return true
if the string is valid, and false
otherwise. Consider edge cases, such as an empty string, or a string containing only one type of bracket. Explain the time and space complexity of your proposed solution. Can you implement the solution in Python?
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
A naive approach would involve iterating through the string and checking for adjacent pairs that can be removed (e.g., "()", "{}", "[]"). This process would repeat until either the string is empty (valid) or no more pairs can be removed (invalid).
While this might work for some simple cases, it's inefficient and doesn't handle nested structures correctly.
The optimal approach involves using a stack to keep track of opening brackets. Here's how it works:
(
, {
, or [
), push it onto the stack.)
, }
, or ]
):
def isValid(s: str) -> bool:
stack = []
mapping = {")": "(", "}": "{", "]": "["}
for char in s:
if char in mapping:
top_element = stack.pop() if stack else '#'
if mapping[char] != top_element:
return False
else:
stack.append(char)
return not stack