标签:lan not 空间 rom 删除 return int str one
给你一个链表,删除链表的倒数第N个结点.
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int):
def getLength(head: ListNode) -> int:
length = 0
while head:
length += 1
head = head.next
return length
dummy = ListNode(0, head)
length = getLength(head)
cur = dummy
for i in range(1, length - n + 1):
cur = cur.next
cur,next = cur.next.next
return dummy.next
时间复杂度:O(L)
空间复杂度: O(1)
判断给定的字符串中括号是否匹配
class Soution:
def isValid(self,s:str) -> bool:
if len(s) % 2 == 1:
return False
pairs = {
")" : "(",
"]" : "[",
"}" : "{",
}
stack = list()
for ch in s:
if ch in pairs:
if not stack or stack [-1] : stack[-1] == pairs[ch]:
return False
stack.pop()
else:
stack.append(ch)
return not stack
时间复杂度:O(L)
空间复杂度:O (L)
将两个升序链表合并成一个新的升序链表并返回
class Solution:
def mergeTwoLists(self, l1, l2):
if l1 is None:
return l2
elif l2 is None:
return l1
elif l1.val < l2.val:
l1.next = self.mergeTwoLists(l1.next, l2)
else:
l2.next = self.mergeTwoLists(l1, l2.next)
return l2
时间复杂度: O(n+m)
空间复杂度:O(n+m)
数字 n 代表生成括号的对数,设计一个函数,用于能够生成所有可能的并且 有效的 括号组合。
class Solution:
def generateParenthesis(self, n:int) -> List(str):
ans = [ ]
def backtrack(S, left, right):
if len(S) == 2 * n:
ans.append(‘ ‘.join(S))
return
if left < n:
S.append(‘(‘)
backtrack(S, left + 1, right)
S.pop()
if right < left:
S.append(‘)‘)
backtrack(S, left, right + 1)
S.pop()
backtrack([ ], 0, 0)
return ans
标签:lan not 空间 rom 删除 return int str one
原文地址:https://www.cnblogs.com/tianle1998/p/14819995.html