struct Node {
int val;
Node *left;
Node *right;
Node *next;
}
填充它的每个 next 指针,让这个指针指向其下一个右侧节点。如果找不到下一个右侧节点,则将 next 指针设置为 NULL。
初始状态下,所有 next 指针都被设置为 NULL。
示例:
class Solution(object):
def connect(self, root):
#不需要判断root.right是否为null
if root and root.left:
root.left.next = root.right
if root.next:
root.right.next = root.next.left
self.connect(root.left)
self.connect(root.right)
return root
给定一个非负整数 numRows,生成杨辉三角的前 numRows 行。
class Solution(object):
def generate(self, numRows):
res = []
for i in range(numRows):
#生成长度为i+1的列表
ans = [1] * (i+1)
for j in range(1,i):
ans[j] = res[-1][j] + res[-1][j-1]
res.append(ans)
return res
给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。
说明:本题中,我们将空字符串定义为有效的回文串。
示例 1:
输入: “A man, a plan, a canal: Panama”
输出: true
示例 2:
输入: “race a car”
输出: false
class Solution(object):
def isPalindrome(self, s):
if not s or not len(s):
return True
import re
# 替换所有非数字字母并转换成小写
s = re.sub('[\W]','',s).lower()
for i in range(len(s)/2):
if s[i] !=s[-i-1]:
return False
return True
给定一个链表,每个节点包含一个额外增加的随机指针,该指针可以指向链表中的任何节点或空节点。
要求返回这个链表的深拷贝。
class Solution(object):
def copyRandomList(self, head):
if head==None:
return None
node = head
map = {}
while node:
#先复制一遍数据
map[node] = Node(node.val,None,None)
node = node.next
node = head
while node:
#复制next和random指针
map[node].next = map[node.next] if node.next else None
map[node].random = map[node.random] if node.random else None
node = node.next
return map[head]
根据逆波兰表示法,求表达式的值。
有效的运算符包括 +, -, *, / 。每个运算对象可以是整数,也可以是另一个逆波兰表达式。
说明:
整数除法只保留整数部分。
给定逆波兰表达式总是有效的。换句话说,表达式总会得出有效数值且不存在除数为 0 的情况。
示例 1:
输入: [“2”, “1”, “+”, “3”, “*”]
输出: 9
解释: ((2 + 1) * 3) = 9
示例 2:
输入: [“4”, “13”, “5”, “/”, “+”]
输出: 6
解释: (4 + (13 / 5)) = 6
class Solution(object):
def evalRPN(self, tokens):
s = []
for c in tokens:
if c.isdigit() or ('-' in c and len(c)>1):
s.append(int(c))
else:
b,a = s.pop(),s.pop()
if c == '+':
s.append(a+b)
elif c == '-':
s.append(a-b)
elif c == '*':
s.append(a*b)
elif c == '/':
# 6 / -132 = -1?
s.append(int(float(a)/b))
return s[0]