1.最大回文长度(动态规划)
class Solution:
def longestPalindrome(self, s: str) -> str:
size = len(s)
max_len = 1
start = 0
matrix = [[False for _ in range(size)] for _ in range(size)]
for i in range(size):
matrix[i][i] = True
for j in range(1, size):
for i in range(0, j):
if s[i] == s[j]:
if j - i < 3:
matrix[i][j] = True
else:
matrix[i][j] = matrix[i+1][j-1]
if matrix[i][j]:
if (j - i + 1) > max_len:
max_len = j - i + 1
start = i
return s[start: start+max_len]
if __name__ == '__main__':
s = Solution()
test = 'cfgabcbadsf'
res = s.longestPalindrome(test)
print(res)
2.给定一个字符串,请你找出其中不含有重复字符的最长子串的长度(动态规划),也可以用滑动窗口求解。
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
if not s:
return 0
max_len = 1
def find_left(s, i):
tmp = s[i]
j = i - 1
while j >= 0 and s[j] not in tmp:
tmp += s[j]
j -= 1
return len(tmp)
for i in range(len(s)):
max_len = max(max_len, find_left(s, i))
return max_len
3.给定两个大小为 m 和 n 的正序(从小到大)数组 nums1 和 nums2。请你找出这两个正序数组的中位数,并且要求算法的时间复杂度为 O(log(m + n))。(两种方法)
class Solution:
def findMedianSortedArrays(self, nums1, nums2) -> float:
def getKthElement(k):
index1, index2 = 0, 0
while True:
# 特殊情况
if index1 == m:
return nums2[index2 + k - 1]
if index2 == n:
return nums1[index1 + k - 1]
if k == 1:
return min(nums1[index1], nums2[index2])
# 正常情况
newIndex1 = min(index1 + k // 2 - 1, m - 1)
newIndex2 = min(index2 + k // 2 - 1, n - 1)
pivot1, pivot2 = nums1[newIndex1], nums2[newIndex2]
if pivot1 <= pivot2:
k -= newIndex1 - index1 + 1
# index 相当于保存了一个位移值
index1 = newIndex1 + 1
else:
k -= newIndex2 - index2 + 1
index2 = newIndex2 + 1
m, n = len(nums1), len(nums2)
totalLength = m + n
if totalLength % 2 == 1:
return getKthElement((totalLength + 1) // 2)
else:
return (getKthElement(totalLength // 2) + getKthElement(totalLength // 2 + 1)) / 2
class Solution:
def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
m = len(nums1)
n = len(nums2)
if m > n:
nums1, nums2, m, n = nums2, nums1, n, m
# nums1数组可以有right种分法
left = 0
right = m
k = (m + n + 1) // 2
# 找出A1,B1,A2,B2重构数组后的满足max(A1, B1)<=min(A2, B2)
while left < right:
mid = left + (right - left) // 2
i = k - mid
if nums1[mid] < nums2[i-1]:
left = mid + 1
else:
right = mid
mid = left
i = k - mid
# 边界条件
if mid > 0:
c1 = nums1[mid - 1]
else:
c1 = float("-inf")
if i > 0:
c1 = max(c1, nums2[i - 1])
else:
c1 = max(c1, float("-inf"))
if (m + n) % 2 == 1:
return c1
if mid < m:
c2 = nums1[mid]
else:
c2 = float("inf")
if i < n:
c2 = min(c2, nums2[i])
else:
c2 = min(c2, float("inf"))
return (c1 + c2) / 2