Skip to content

Commit 4d0a8b0

Browse files
authored
Merge pull request #12 from Vikas-Mahana/vikas
valid paranthesis
2 parents aeeed24 + f977b88 commit 4d0a8b0

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

valid_parathesis.py

+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
"""
2+
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
3+
4+
An input string is valid if:
5+
6+
Open brackets must be closed by the same type of brackets.
7+
Open brackets must be closed in the correct order.
8+
Every close bracket has a corresponding open bracket of the same type.
9+
"""
10+
11+
def isValid(self, s: str) -> bool:
12+
# Dictionary to store matching brackets
13+
brackets = {')': '(', '}': '{', ']': '['}
14+
15+
# Stack to keep track of opening brackets
16+
stack = []
17+
18+
# Iterate through each character in the string
19+
for char in s:
20+
# If it's a closing bracket
21+
if char in brackets:
22+
# Check if stack is empty or top doesn't match
23+
if not stack or stack[-1] != brackets[char]:
24+
return False
25+
# Pop the matching opening bracket
26+
stack.pop()
27+
else:
28+
# Push opening bracket onto stack
29+
stack.append(char)
30+
31+
# Return True if stack is empty, False otherwise
32+
return len(stack) == 0

0 commit comments

Comments
 (0)