1.两数相加
给你两个 非空 的链表,表示两个非负的整数。它们每位数字都是按照 逆序 的方式存储的,并且每个节点只能存储 一位 数字。
请你将两个数相加,并以相同形式返回一个表示和的链表。
你可以假设除了数字 0 之外,这两个数都不会以 0 开头。
示例 1:
输入:l1 = [2,4,3], l2 = [5,6,4] 输出:[7,0,8] 解释:342 + 465 = 807.
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
cur = 0
n1, n2 = l1, l2
head = ListNode()
node = head
while n1 or n2 or cur:
if n1:
cur += n1.val
n1 = n1.next
if n2:
cur += n2.val
n2 = n2.next
node.next = ListNode(cur % 10)
node = node.next
cur //= 10
return head.next
2.无重复字符的最长字串
给定一个字符串 s
,请你找出其中不含有重复字符的 最长子串 的长度。
示例 1:
输入: s = "abcabcbb" 输出: 3 解释: 因为无重复字符的最长子串是 "abc"
,所以其长度为 3。
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
if not s:
return 0
res = []
max_length = 0
for i in s:
if i in res:
index = res.index(i)
res = res[index+1:]
res.append(i)
max_length = max(len(res),max_length)
return max_length
3.最长回文子串
给你一个字符串 s
,找到 s
中最长的回文子串。
如果字符串的反序与原始字符串相同,则该字符串称为回文字符串。
示例 1:
输入:s = "babad" 输出:"bab" 解释:"aba" 同样是符合题意的答案。
class Solution:
def longestPalindrome(self, s: str) -> str:
n = len(s)
if n < 2:
return s
max_len = 1
begin = 0
dp = [[False] * n for _ in range(n)]
for i in range(n):
dp[i][i] = True
for L in range(2, n + 1):
for i in range(n):
j = L + i - 1 if j >= n:
break
if s[i] != s[j]:
dp[i][j] = False
else:
if j - i < 3:
dp[i][j] = True
else:
dp[i][j] = dp[i + 1][j - 1]
if dp[i][j] and j - i + 1 > max_len:
max_len = j - i + 1
begin = i
return s[begin:begin + max_len]