-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
45 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
""" | ||
Of course! Here's another coding exercise for you: | ||
Problem: Valid Parentheses | ||
Given a string containing only the characters '(', ')', '{', '}', '[' and ']', | ||
determine if the input string is valid. An input string is valid if: | ||
Open brackets are closed by the same type of brackets. | ||
Open brackets are closed in the correct order. | ||
Note: | ||
An empty string is also considered valid. | ||
Write a function called is_valid_parentheses that takes a string s as input and returns True if the input string is valid, | ||
and False otherwise. | ||
""" | ||
|
||
VALID_VALUES = [ | ||
"()", | ||
"{}", | ||
"[]" | ||
] | ||
|
||
def is_valid_parentheses(s: str) -> bool: | ||
result = None | ||
|
||
while result == None: | ||
if len(s) == 0: | ||
result = True | ||
break | ||
if not any(substr in s for substr in VALID_VALUES): | ||
result = False | ||
break | ||
|
||
for substr in VALID_VALUES: | ||
s = s.replace(substr, "") | ||
|
||
return result | ||
|
||
print(is_valid_parentheses("()")) # Output: True | ||
print(is_valid_parentheses("()[]{}")) # Output: True | ||
print(is_valid_parentheses("{[()]}")) # Output: True | ||
print(is_valid_parentheses("([)]")) # Output: False | ||
print(is_valid_parentheses("{{{{")) # Output: False | ||
print(is_valid_parentheses("")) # Output: True |