记录一下python-leetcode（一）

def Longeststring(s):
k = [] #存放不重复字符
w = [] #存放长度
longth = 0
if len(s) == 0:
return 0
if len(s) == 1:
return 1
for j in range(len(s) - 1):
for i in range(j, len(s)):
if i == len(s) - 1 and s[i] not in k:
longth += 1
w.append(longth)
return max(w)
if s[i] not in k:
longth += 1
k.append(s[i])
else:
w.append(longth)
longth = 0
k.clear() #当找到重复字符的时候把k clear
return max(w)


def lengthOfLongestSubstring(self, s: str) -> int:
dict = {} #存放不同字符串
longth = 0 #不重复的长度长度
start = 0 #开始的位置
for index, item in enumerate(s):
if item in dict:
longth = max(longth, index - start) #如何找到了重复字符，更新长度
start = max(start, dict[item] + 1) #更新开始的位置
dict[item] = index #更新字典
return max(longth, len(s) - start)


a=[1, 2] b=[3,4] 输出：（2+3）/ 2 = 2.5

def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
# 组合后的数组长度为偶数： ((mid) + (mid+1)) / 2
# 长度为奇数输出 merged[len(merged)//2]
# 比较困难的是排序时间复杂度为 O(n+m). 但是得达到O(log(n+m))
def merge(A, B):
i, j = 0, 0
res = []
while i < len(A) and j < len(B):
if A[i] <= B[j]:
res.append(A[i])
i += 1
else:
res.append(B[j])
j += 1
if i < len(A):
res += A[i:] #如果B完事了，直接把A全部append
if j < len(B):
res += B[j:]
return res
merged = merge(nums1, nums2)
mid = (len(merged) - 1) // 2
if len(merged) % 2 == 0:
return (merged[mid] + merged[mid + 1]) / 2
else:
return merged[mid]



def findMedianSortedArrays(self, nums1, nums2):
x = sorted(nums1 + nums2)
median = None
n = len(x) // 2
if len(x) % 2 == 1:
median = x[n]
else:
median = (x[n] + x[n - 1]) / 2
return median


def longestPalindrome(self, s):
if len(s) < 2 or s == s[::-1]: #处理最简单的状况
return s
max_len = 1
start = 0
for i in range(1, len(s)):
even = s[i - max_len: i + 1]
odd = s[i - max_len - 1: i + 1]
if i - max_len - 1 >= 0 and odd == odd[::-1]:
start = i - max_len - 1 # 记录开始的位置
max_len += 2  # 不看max_len 长度差2，所以+2
continue  # 由于even跟odd长度只差了1，所以满足前者不可能满足后面的条件，所以直接continue
if i - max_len >= 0 and even == even[::-1]:
start = i - max_len
max_len += 1
return s[start: start + max_len]


04-24 1761
03-03 437
08-30 1388