题目14 :求数组中的最大匹配前缀
题目要求:比如输入list[‘abc’,’abcd’,’ab’]
则需要返回‘ab’
我的思路是让每个数与str[0]比较,每一次比较完获得一个最大匹配前缀后,更新c,回到循环进行下一次的比较,用python进行实现。
代码如下:
class Solution(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if len(strs) == 0:
return ""
c = strs[0]
if len(strs)==1:
return c
else:
for i in strs[1:]:
l = min(len(c), len(i))
for j in range(l):
if c[0:j + 1] == i[0:j + 1]:
m = c[0:j + 1]
else:
if j == 0:
m = None
c = m
return m
strs = ['abc','ab','abcd']
s = Solution()
print(s.longestCommonPrefix(strs))
输出结果为:
题目7:翻转整数
题目要求:输入321,输出123
我的分析:要解决的问题1:负数的问题,我的思路是加入一个flag, 作为正负数的判断,若是负数则将其变为正数处理,最后再添上负号。
要解决的问题2:若是两位数,需要分情况讨论,避免出现输入是12,输出是210的状况。
我的代码如下:
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
flag = 0
if (x < 0):
x = - x
flag = 1
a1 = int( x / 100 ) # 百位
a2 = int(( x - a1 * 100) / 10) # 十位
a3 = x % 10 # 个位
if a1 == 0:
if a2 == 0:
ans = a3
else:
ans = a3 * 10 + a2
else:
ans = a3 * 100 + a2 * 10 + a1
if (flag):
ans = -ans
return ans
b = Solution()
print(b.reverse(123))
print(b.reverse(-123))
print(b.reverse(15))
结果: