r/learnprogramming • u/shaynjam • 12h ago
Solved im kinda proud of this solution i wrote even though it was an "easy" i still felt like i grew a lot
the problem:
Given a string s 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.
- Every close bracket has a corresponding open bracket of the same type.
Example 1:
Input: s = "()"
Output: true
Example 2:
Input: s = "()[]{}"
Output: true
Example 3:
Input: s = "(]"
Output: false
Example 4:
Input: s = "([])"
Output: true
Example 5:
Input: s = "([)]"
Output: false
my solution: (on leetcode)
class Solution:
def isValid(self, s: str) -> bool:
inputs = {
"(":1,
")":9,
"{":2,
"}":8,
"[":3,
"]":7}
prev_bracket=[]
if(len(s)%2!=0):
return False
for a in s:
if inputs[a]<4:
prev_bracket.append(inputs[a])
else:
if len(prev_bracket)==0:
return False
x=prev_bracket.pop()
if x+inputs[a]!=10:
return False
return len(prev_bracket)==0