File tree Expand file tree Collapse file tree 2 files changed +36
-2
lines changed Expand file tree Collapse file tree 2 files changed +36
-2
lines changed Original file line number Diff line number Diff line change @@ -9,8 +9,9 @@ def longestCommonPrefix(strs):
9
9
return ""
10
10
output = "" # empty output
11
11
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 ):
14
15
output += shortest_str [i ] # add character to output
15
16
else :
16
17
break # otherwise return empty output
Original file line number Diff line number Diff line change
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
You can’t perform that action at this time.
0 commit comments