Write a function to find the longest common prefix string amongst an array of strings.
想法比较直接,注意这里shortest的使用方法和min的使用方法。 class Solution(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if not strs:
return ""
shortest = min(strs, key=len)
for i in range(len(shortest)):
for s in strs:
if not s[i] == shortest[i]:
return shortest[:i]
return shortest
注意这里一开始对各种情况的处理。 在if的条件语句中,if 和 else都要出现,详见下面的例子。
class Solution(object):
def myAtoi(self, str):
"""
:type str: str
:rtype: int
"""
if len(str) == 0:
return 0
isNegative, i, result = False, 0, 0
while i < len(str) and str[i] == ' ':
i = i + 1
if i == len(str):
return 0
isNegative = str[i] == '-'
i += 1 if str[i] == '-' or str[i] == '+' else 0
cnt = 0
while i < len(str) and cnt <= 10:
t = ord(str[i]) - ord('0')
if 0 <= t <= 9:
result = result*10 + t
else:
break
i = i + 1
cnt = cnt + 1
result = -1 * result if isNegative else result
if result >= 2147483647:
return 2147483647
elif result <= -2147483648:
return -2147483648
else:
return result