📅  最后修改于: 2023-12-03 14:56:43.693000             🧑  作者: Mango
这是一个算法样本问题复发的套装2,包含以下问题:
实现一个函数,输入一个链表,输出该链表中倒数第k个节点。
示例:
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def findKthToTail(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
"""
if not head or k <= 0:
return None
p1 = head
p2 = head
for i in range(k - 1):
if not p1.next:
return None
p1 = p1.next
while p1.next:
p1 = p1.next
p2 = p2.next
return p2
给定一个字符串,判断该字符串是否为回文字符串。回文字符串是指正反顺序都相同的字符串。
示例:
class Solution:
def isPalindrome(self, s: str) -> bool:
"""
:type s: str
:rtype: bool
"""
s = ''.join(filter(str.isalnum, s)).lower()
return s == s[::-1]
实现一个函数,在一个有序数组中查找两个数,使它们的和为 target。请返回这两个数的下标。假设每个输入只对应一个答案,且同样的元素不能被重复利用。
示例:
class Solution:
def twoSum(self, numbers, target):
"""
:type numbers: List[int]
:type target: int
:rtype: List[int]
"""
left, right = 0, len(numbers)-1
while left < right:
if numbers[left] + numbers[right] == target:
return [left+1, right+1]
elif numbers[left] + numbers[right] < target:
left += 1
else:
right -= 1
return None
示例:
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
d = {}
for i, num in enumerate(nums):
if target - num in d:
return [d[target-num], i]
d[num] = i
return None
给定一个字符串 s,找到 s 中最长的回文子串。你可以假设 s 的最大长度为1000。
示例:
class Solution:
def longestPalindrome(self, s: str) -> str:
"""
:type s: str
:rtype: str
"""
def palindrome(s):
return s == s[::-1]
n = len(s)
max_len = 1
res = s[0]
for i in range(n):
for j in range(i + 1, n):
if j - i + 1 > max_len and palindrome(s[i:j+1]):
max_len = j - i + 1
res = s[i:j+1]
return res