From ba5483bd65b7b1a9d02c24f1087b3e08e24dac7f Mon Sep 17 00:00:00 2001 From: Yuri Date: Sun, 19 Jul 2020 14:51:22 +0300 Subject: [PATCH] Python solution for problem # 20 new solution and readme update --- Python/20_ValidParentheses.py | 31 +++++++++++++++++++++++++++++++ README.md | 12 ++++++++++++ 2 files changed, 43 insertions(+) create mode 100644 Python/20_ValidParentheses.py diff --git a/Python/20_ValidParentheses.py b/Python/20_ValidParentheses.py new file mode 100644 index 00000000..17c2d336 --- /dev/null +++ b/Python/20_ValidParentheses.py @@ -0,0 +1,31 @@ +# -*- coding: utf-8 -*- +#Difficulty: Easy +#Runtime: 82.23% +#Memory Usage: 64.83% + +""" +Algorithm: + 1. Check a bracket (b) in the string (s), if it contains in parentheses + dictionary then we add to stack it's opposite bracket. + 2. If bracket not in parentheses we check does it mach with last bracket in + the stack, also we check if stack exists while iterating through the string. + If one of this conditions is not True - return False immediately. + 3. After we checked whole string we need to check is stack empty or not and + return result. + 4. Result will be true if stack is empty it means all parentheses are valid + and closed in the correct order. + +Time Complexity = O(n) +Space Complexity = O(n) +""" + +class Solution: + def isValid(self, s: str) -> bool: + parentheses = {'(':')', '{':'}', '[':']'} + stack = [] + for b in s: # take bracket 'b' from string 's' + if b in parentheses: # if bracket in parentheses + stack.append(parentheses[b]) # append it's opposite to stack + elif not stack or stack.pop() != b: # if not stack or bracket not + return False # equal last bracket in stack + return not stack # if stack still exists -> False else True \ No newline at end of file diff --git a/README.md b/README.md index 7648412c..86550ff5 100644 --- a/README.md +++ b/README.md @@ -100,6 +100,18 @@
+## Stack +| # | Title | Solution | Time | Space | Difficulty | Tag | Note| +|-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------|-----| +|020|[Valid Parentheses](https://leetcode.com/problems/valid-parentheses/)|[Python](./Python/20_ValidParentheses.py)|_O(n)_|_O(n)_|Easy|Stack|| + +
+
+ ⬆️ Back to Top +
+
+ + ## Graph | # | Title | Solution | Time | Space | Difficulty | Tag | Note| |-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------|-----|