1 两数之和(题目链接)
class Solution: # 一次哈希法 def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ m = {} for i in range(len(nums)): minus = target - nums[i] if minus in m and i != m[minus]: return [i, m[minus]] m[nums[i]] = i return None
2 两数相加(题目链接)
class Solution: def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ up = 0 l3 = ListNode(0) l3_head = l3 while l1 or l2: if l1 is None: l1 = ListNode(0) if l2 is None: l2 = ListNode(0) sum = l1.val + l2.val + up if sum > 9: sum = sum - 10 l3.next = ListNode(sum) up = 1 else: l3.next = ListNode(sum) up = 0 l1 = l1.next l2 = l2.next l3 = l3.next if up > 0: l3.next = ListNode(up) return l3_head.next
3 无重复字符的最长子串(题目链接)
class Solution: def lengthOfLongestSubstring(self, s): """ :type s: str :rtype: int """ num = 0 temp = [] for item_s in s: if item_s in temp: index = temp.index(item_s) + 1 temp = temp[index:] temp.append(item_s) else: temp.append(item_s) if len(temp) > num: num = len(temp) return num
4 寻找两个有序数组的中位数(题目链接)
class Solution: def findMedianSortedArrays(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: float """ sum = (len(nums1) + len(nums2)) index = sum//2 + 1 p1 = 0 p2 = 0 max1 = 0 max2 = 0 for item in range(index): max2 = max1 if p1 == len(nums1): max1 = nums2[p2] p2 += 1 elif p2 == len(nums2): max1 = nums1[p1] p1 += 1 elif nums1[p1] > nums2[p2]: max1 = nums2[p2] p2 += 1 else: max1 = nums1[p1] p1 += 1 if sum%2 == 1: return max1 else: return (max1 + max2)/2
5 最长回文子串(题目链接)
Manacher算法(“马拉车算法”,中心扩展法+不重复判断)
讲解链接:https://www.jianshu.com/p/116aa58b7d81
https://www.cnblogs.com/nkqlhqc/p/9005450.html
class Solution: def longestPalindrome(self, s): """ :type s: str :rtype: str """ if s == '': return '' sp = '' sp_len = 2*len(s)+2 radius = [0 for o in range(sp_len)] # 回文半径列表 index_max = -1 # 最大回文子串中间所在index r_max = -1 # 最大回文子串右边界 def plalindrome(index, r_i=1): while(sp[index-r_i] != '$' and sp[index+r_i] != '$' and sp[index-r_i] == sp[index+r_i]): r_i += 1 return r_i for item in range(len(s)): # 字符串的字符间加'#'与'$' sp += ''.join(['#', s[item]]) sp = ''.join(['$', sp, '#$']) for i in range(sp_len): # 计算回文半径,填充半径列表 if i >= r_max: radius[i] = plalindrome(i) if r_max < radius[i]: r_max = radius[i] index_max = i elif r_max - i <= radius[2 * index_max - i]: radius[i] = radius[2 * index_max - i] else: radius[i] = plalindrome(i, radius[2 * index_max - i] + 1) if r_max < radius[i]: r_max = radius[i] index_max = i result = sp[index_max - radius[index_max] + 1: index_max + radius[index_max]] return result.replace('#', '')