GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — coding-problems/Other/valid_parentheses.py at master · Pranshu-Raj/coding-problems Expand file tree/ Copy pathvalid_parentheses.pyMore file actions 60 lines (45 loc) · 1.2 KB / Copy pathvalid_parentheses.pyFile metadata and controls60 lines (45 loc) · 1.2 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 ''' Valid Parentheses Given a string of round, curly, and square open and closing brackets, return whether the brackets are balanced (well-formed). For example, given the string '([])[]({})', you should return true. Given the string '([)]' or '((()', you should return false. Input: '()[{([]{})}]' Output: True ========================================= Use stack. Add open brackets in the stack, remove the last bracket from the stack if there is a closing brackets. Time Complexity: O(N) Space Complexity: O(N) ''' ############ # Solution # ############ from collections import deque def is_valid(string): closing = { '}': '{', ']': '[', ')': '(' } stack = deque() for char in string: if char in closing: if len(stack) == 0: return False last = stack.pop() if last != closing[char]: return False else: stack.append(char) return True ########### # Testing # ########### # Test 1 # Correct result => True print(is_valid('()[{([]{})}]')) # Test 2 # Correct result => False print(is_valid('()[{([]{]})}]')) # Test 3 # Correct result => False print(is_valid('(]]])')) |
| You are visitor 01402792 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |