LeetCode02:两数相加
You are given two non-empty linked lists representing two non-negative integers.
The digits are stored in reverse order,
and each of their nodes contains a single digit.
Add the two numbers and return the sum as a linked list.
You may assume the two numbers do not contain any leading zero,
except the number 0 itself.
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
result = ListNode(-1)
l3 = result
flag = 0
while l1 is not None and l2 is not None:
a = l1.val
b = l2.val
c = a + b + flag
l3.next = ListNode(c % 10)
flag = 1 if c >= 10 else 0
l1 = l1.next
l2 = l2.next
l3 = l3.next
while l1 is not None:
a = l1.val + flag
l3.next = ListNode(a % 10)
flag = 1 if a >= 10 else 0
l1 = l1.next
l3 = l3.next
while l2 is not None:
b = l2.val + flag
l3.next = ListNode(b % 10)
flag = 1 if b >= 10 else 0
l2 = l2.next
l3 = l3.next
if flag == 1:
l3.next = ListNode(flag)
return result.next
LeetCode04:寻找两个正序数组的中位数
Given two sorted arrays nums1 and nums2 of size m and n respectively,
return the median of the two sorted arrays.
Follow up: The overall run time complexity should be O(log (m+n)).
class Solution:
def findMedianSortedArrays(self, nums1, nums2):
m = len(nums1)
n = len(nums2)
nums1.extend(nums2)# 合并
nums1.sort()# 排序
if (m + n) & 1:# 如果是奇数 返回中位数
return nums1[(m + n - 1) >> 1]
else:# 返回两个中位数的平均值
return (nums1[(m + n - 1) >> 1] + nums1[(m + n) >> 1]) / 2
LeetCode05:最长回文子串
Given a string s, return the longest palindromic substring in s.
class Solution:
def longestPalindrome(self, s: str) -> str:
count = len(s)
if count == 0 or count == 1:
return s
longestPalindromelen = 1
longestPalindromeStr = s[0:1]
dp = [[False] * count for i in range(count)]
for r in range(1, count):
for l in range(0, r):
if s[r] == s[l] and (r - l <= 2 or dp[l + 1][r - 1] == True):
dp[l][r] = True
if longestPalindromelen < r - l + 1:
longestPalindromelen = r - l + 1
longestPalindromeStr = s[l:l + longestPalindromelen]
return longestPalindromeStr
team-learning-program/LeetCodeTencent/002 两数相加 .md
team-learning-program/LeetCodeTencent/004 寻找两个正序数组的中位数.md
team-learning-program/LeetCodeTencent/005 最长回文子串.md
下面这篇文章提出利用马拉车算法求解最长回文子串问题。
[LeetCode] 5. Longest Palindromic Substring 最长回文子串