Skip to content

Commit c60c70b

Browse files
committed
added changes to common_pref and added new solution
1 parent 7838091 commit c60c70b

File tree

2 files changed

+36
-2
lines changed

2 files changed

+36
-2
lines changed

common_pref.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,9 @@ def longestCommonPrefix(strs):
99
return ""
1010
output = "" # empty output
1111
shortest_str = min(strs, key=len) # get the shortest string in the list
12-
for i in range(len(shortest_str)): # check each characters of the shortest string
13-
if all(s[i] == shortest_str[i] for s in strs): # check if every string have the same character at index i
12+
for i in range(len(shortest_str)): # check each characters of the shortest string
13+
# check if every string have the same character at index i
14+
if all(s[i] == shortest_str[i] for s in strs):
1415
output += shortest_str[i] # add character to output
1516
else:
1617
break # otherwise return empty output

parentheses.py

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
# Learn Python together
2+
"""Write a python program to check parentheses is valid or not"""
3+
4+
# Solution 1 using for loop, append and pop methods
5+
def isValid(strs):
6+
open_parenth = ["(", "[", "{"]
7+
close_parenth = [')', ']', "}" ]
8+
stack = []
9+
10+
for char in strs:
11+
if char in open_parenth:
12+
stack.append(char)
13+
elif char in close_parenth:
14+
# check if empty stack or if the last item in the stack matches the current char
15+
if not stack or open_parenth.index(stack[-1]) != close_parenth.index(char):
16+
return False
17+
stack.pop() # pop method used for removing the last char
18+
return not stack
19+
# check
20+
print(isValid("()[]{")) # False
21+
print(isValid("()[]{}")) # True
22+
23+
# Solution 2 using while loop, any and replace methods
24+
def isValid2(strs):
25+
list_parentheses = ["[]", "()", "{}"]
26+
# iteration for any chars in strs and list and check if they are matched
27+
while any(char in strs for char in list_parentheses):
28+
for par in list_parentheses:
29+
strs = strs.replace(par, "") # if are matched remove last char
30+
return not strs
31+
# check
32+
print(isValid2("()[]{")) # False
33+
print(isValid2("()[]{}")) # True

0 commit comments

Comments
 (0)