左旋转字符串
class Solution(object):
def reverseLeftWords(self, s, n):
"""
:type s: str
:type n: int
:rtype: str
"""
# 方法一 时间复杂度为N
#return s[n:] + s[:n]
# 方法二
res = []
for i in range(n,len(s)):
res.append(s[i])
for i in range(n):
res.append(s[i])
return ''.join(res)
2.翻转字符串
s = 'hello'
print(s[::-1])
翻转二叉树
class Solution(object):
def invertTree(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
if is not root:
return None
root.left,root.right = root.right,root.left
self.invertTree(root.left)
self.invertTree(root.right)
return root
# x 不为空时,为真,对真取反,变成假
if not x
最大二叉树(第654道试题)
class Solution(object):
def constructMaximumBinaryTree(self, nums):
"""
:type nums: List[int]
:rtype: TreeNode
"""
if not nums:
return None
# # 由于没有重复元素, 所以获取最大元素部分代码等价的
# # max_v, m_i = float(-inf), 0
# # for i, v in enumerate(nums):
# # if v>max_v:
# # max_v = v
# # m_i = i
max_v = max(nums)
max_i = nums.index(max_v)
root = TreeNode(max_v)
root.left = self.constructMaximumBinaryTree(nums[:max_i])
root.right = self.constructMaximumBinaryTree(nums[max_i+1:])
return root
tips:
1.list.index()可以直接获取value的下标
2.递归是左子树,右子树的递归self.constructMaximumBinaryTree(nums[:max_i
是错误的写法,正确写法:root.left = self.constructMaximumBinaryTree(nums[:max_i])
3.注意的递归的区间:左子树的区间:[:max_i],右子树的区间是[max_i+1:]
4.float(-inf) 表示无穷小,float(inf)表示无穷大
报错:
错误描述:缩进不匹配
IndentationError: unindent does not match any outer indentation level
原因:TAB键和空格键混合输入了
解决办法:把空格删除
错误描述:递归报错
RuntimeError: maximum recursion depth exceeded
原因:递归函数写的不对,在本题中递归函数的右子树的区间是[max_i+1:]
而不是右子树的区间是[max_i:]
反转链表(第206道题)
试题连接:https://leetcode-cn.com/problems/reverse-linked-list/
lass Solution(object):
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
# not 取反操作;not x
# 如果x 为true,则返回false,x为false,则返回true
# if not x 中(x一定要为true,才会走if语句块)
# if not x
if not head or head.next == None:
return head
# 这里已经将链表反转完毕
last = self.reverseList(head.next)
# 调整反转链表的指向
head.next.next = head
head.next = None
return last
参考解析
https://labuladong.gitbook.io/algo/shu-ju-jie-gou-xi-lie/2.2-shou-ba-shou-shua-lian-biao-ti-mu-xun-lian-di-gui-si-wei/di-gui-fan-zhuan-lian-biao-de-yi-bu-fen
问题:NoneType' object has no attribute
原因:这个问题的出现一般是某个变量是空,也就是’NoneType’类型导致的
仔细检查空变量的情况