# ● 24. 两两交换链表中的节点
class ListNode:
def __init__(self, val = 0, next = None):
self.val = val
self.next = next
class Solution:
def swapPairs(self, head:ListNode) -> ListNode:
res = ListNode(next = head)
pre = res
while pre.next and pre.next.next:
cur = pre.next
post = pre.next.next
# pre, cur, post
cur.next = post.next
post.next = cur
pre.next = post
pre = pre.next.next
return res.next
# ● 19.删除链表的倒数第N个节点
# Carl给的方法比我之前的方法更高效,故更改方法
def removeNthFromEnd(self, head, n:int):
# hh = head
# count = 0
# while hh:
# hh = hh.next
# count += 1
# if count == 1 and n == 1: return None
# res = count - n
# cur = head
# tmp = cur
# for _ in range(res-1):
# tmp = tmp.next
# if tmp.next:
# tmp.next = tmp.next.next
# return cur
dummy_head = ListNode()
dummy_head.next = head
slow, fast = dummy_head, dummy_head
while (n!=0):
fast = fast.next
n -= 1
while fast.next:
slow = slow.next
fast = fast.next
slow.next = slow.next.next
return dummy_head.next
# ● 面试题 02.07. 链表相交
def getIntersectionNode(self, headA, headB):
curA = headA
curB = headB
while curA != curB:
curA = curA.next if curA else headB
curB = curB.next if curB else headA
return curA
# ● 142.环形链表II
def detectCycle(self, head: ListNode) -> ListNode:
slow = head
fast = head
while True:
# 小心有fast不存在的情况
if not(fast and fast.next): return
slow = slow.next
fast = fast.next.next
if slow == fast:
break
fast = head
while fast != slow:
slow = slow.next
fast = fast.next
return fast
# LeetCode每日一题 784 字母大小写全排列
print(ord('a'),ord('A'),chr(66))
s = "a1b2"
l_s = list(s)
res = []
def swapA(a):
if ord(a) < 97 and ord(a) >= 65:# A-Z
return chr(ord(a) + 32)
else:
return chr(ord(a) - 32)
def dfs(l_s:list, index:int):
while index < len(l_s) and ord(l_s[index]) < 65:
index += 1
if index == len(l_s):
res.append(''.join(l_s))
return
dfs(l_s, index + 1)
l_s[index] = swapA(l_s[index])
dfs(l_s, index + 1)
l_s[index] = swapA(l_s[index])
dfs(list(s), 0)
print(res)
代码随想录训练营第III期--004--python
最新推荐文章于 2024-07-23 14:36:35 发布