# meaning for list s=[1,2,3,4] c='abcd' print(s[1:4]) print(s[1:3]) print(s[0:3]) print(s[0]) print(s[3]) print(c[1:4]) print(c[1:3]) print(c[0:3]) print(c[0]) print(c[3])
[2, 3, 4] [2, 3] [1, 2, 3] 1 4 bcd bc abc a d
(13) Roman to Integer
I can be placed before V (5) and X (10) to make 4 and 9. X can be placed before L (50) and C (100) to make 40 and 90. C can be placed before D (500) and M (1000) to make 400 and 900.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
classSolution: defromanToInt(self,s): translation={ "I":1, "V":5, "X":10, "L":50, "C":100, "D":500, "M":1000 } number=0 s = s.replace("IV", "IIII").replace("IX", "VIIII") s = s.replace("XL", "XXXX").replace("XC", "LXXXX") s = s.replace("CD", "CCCC").replace("CM", "DCCCC") for char in s: number +=translation[char] return number
ifnot strs: return"" shortest = min(strs,key=len) for i, ch inenumerate(shortest): for other in strs: if other[i] != ch: return shortest[:i] return shortest
(20) Valid Parentheses
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
classSolution: defisValid(self, s): valid_brack = [('{', '}'), ('(', ')'), ('[', ']')] stack = [] for c in s: iflen(stack)>0and (stack[-1], c) in valid_brack: stack.pop() else: stack.append(c) returnlen(stack)==0 solution = Solution() s=")()" result = solution.isValid(s) print(result)
(28) Find the Index of the First Occurrence in a String
1 2 3 4 5 6
classSolution(object): defstrStr(self, haystack, needle): for i inrange(len(haystack)): if haystack[i:i+len(needle)]==needle: return i return -1
(58) Length of Last Word
1 2 3 4 5 6 7 8 9 10 11
# 倒序 deflengthofLastWords(s): length=0 i=len(s)-1 while i>=0and s[i]=='': i-=1 while i>=0and s[i]!='': length+=1 i-=1 return length