class Solution:
def mergeAlternately(self, word1: str, word2: str) -> str:
i, n, m = 0, len(word1), len(word2)
ans = []
while i < n or i < m:
if i < n:
ans.append(word1[i])
if i < m:
ans.append(word2[i])
i+=1
return "".join(ans)
⭐笔记:利用一个i
同时控制两个字符串
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
l, r =0, 0
while r < len(nums):
if l == r or nums[r] == 0:
r += 1
elif nums[l] != 0:
l += 1
else:
nums[l] = nums[r]
nums[r] = 0
return nums
class Solution:
def romanToInt(self, s: str) -> int:
ROMAN = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000}
ans = 0
for x, y in pairwise(s):
x, y = ROMAN[x], ROMAN[y]
ans += x if x >= y else -x
return ans + ROMAN[s[-1]]
pairwise
来源于itertools
模块,用于遍历s序列中的元素对:
将输入的可迭代对象(比如列表、元组等)中的元素按顺序两两配对,然后返回这些配对组成的迭代器。
from itertools import pairwise
s = [1, 2, 3, 4, 5]
for x, y in pairwise(s):
print(x, y)
# 输出:
# 1 2
# 2 3
# 3 4
# 4 5
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
pre = None
cur = head
while cur:
nxt = cur.next
cur.next = pre
pre = cur
cur = nxt
return pre
运用类似“头插法的方式”,重点是要记录链表不同时刻(变换后)首元素的位置
🌈我的分享也就到此结束啦🌈 要是我的分享也能对你的学习起到帮助,那简直是太酷啦! 若有不足,还请大家多多指正,我们一起学习交流! 📢公主,王子:点赞👍→收藏⭐→关注🔍 感谢大家的观看和支持!祝大家都能得偿所愿,天天开心!!!