-
Notifications
You must be signed in to change notification settings - Fork 69
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #41 from akashsara/issue36-valid-parenthesis
Added solution to issue 36 - Valid Parenthesis
- Loading branch information
Showing
1 changed file
with
22 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,22 @@ | ||
#!python3 | ||
|
||
def has_valid_parens(input_string): | ||
""" | ||
CHALLENGE: | ||
Given a string 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. | ||
> Note that an empty string is also considered valid. | ||
DIFFICULTY: INTERMEDIATE [Due to use of stack] | ||
""" | ||
stack = [] | ||
bracket_map = {'[':']', '(':')', '{':'}'} | ||
for bracket in input_string: | ||
if bracket in bracket_map: | ||
stack.append(bracket) | ||
elif len(stack) == 0 or bracket_map[stack.pop()] != bracket: | ||
return False | ||
return len(stack) == 0 |