File tree 2 files changed +61
-0
lines changed
2 files changed +61
-0
lines changed Original file line number Diff line number Diff line change
1
+ # @return a string
2
+ def longestCommonPrefix (strs ):
3
+ l = len (strs )
4
+ if l == 0 :
5
+ return ''
6
+ elif l == 1 :
7
+ return strs [0 ]
8
+ prefix = ''
9
+ a = strs [0 ]
10
+ b = strs [1 ]
11
+ lb = len (b )
12
+ for i in range (len (a )):
13
+ if i >= lb or a [i ] != b [i ]:
14
+ break
15
+ prefix += a [i ]
16
+ if prefix == '' :
17
+ return ''
18
+
19
+ for i in range (2 , len (strs )):
20
+ s = strs [i ]
21
+ ls = len (s )
22
+ for i in range (len (prefix )):
23
+ if i >= ls or s [i ] != prefix [i ]:
24
+ prefix = prefix [0 :i ]
25
+ break
26
+
27
+ return prefix
28
+
29
+ assert longestCommonPrefix ([]) == ''
30
+ assert longestCommonPrefix (['a' , 'b' ]) == ''
31
+ assert longestCommonPrefix (['abc' , 'ab' ]) == 'ab'
32
+ assert longestCommonPrefix (['abc' , 'abcd' , 'abd' ]) == 'ab'
Original file line number Diff line number Diff line change
1
+ # @return a boolean
2
+ def isValid (s ):
3
+ stack = []
4
+ l = 0
5
+ if len (s ) % 2 == 1 :
6
+ return False
7
+ for cha in s :
8
+ if cha == '(' or cha == '[' or cha == '{' :
9
+ stack .append (cha )
10
+ l += 1
11
+ else :
12
+ if l == 0 :
13
+ return False
14
+ if cha == ')' and stack [- 1 ] != '(' :
15
+ return False
16
+ elif cha == ']' and stack [- 1 ] != '[' :
17
+ return False
18
+ elif cha == '}' and stack [- 1 ] != '{' :
19
+ return False
20
+ stack .pop ()
21
+ l -= 1
22
+ return l == 0
23
+
24
+
25
+ assert isValid ('()' ) == True
26
+ assert isValid ('(' ) == False
27
+ assert isValid ('()[]{}' ) == True
28
+ assert isValid ('([])' ) == True
29
+ assert isValid ('([)]' ) == False
You can’t perform that action at this time.
0 commit comments