网易有道9.12笔试(移动开发)
第一题
“樱桃树”——找出二叉树中有多少个带有两个叶子节点的子串
m, n = list(map(int, input().strip().split())) # m个节点,n条边
has_child_node = set() # 存放非叶子节点
tree_graph = [[-1]*2 for _ in range(m+1)] # 行数为节点数+1,即结点下标索引从 1开始,第一列存放左孩子,第二列存放右孩子
for i in range(n):
line = input().strip().split()
node = int(line[0])
has_child_node.add(node)
if line[1] == 'left':
tree_graph[node][0] = int(line[2])
elif line[1] == 'right':
tree_graph[node][1] = int(line[2])
res = 0
for node in has_child_node:
left_child = tree_graph[node][0]
right_child = tree_graph[node][1]
if left_child != -1 and right_child != -1 and tree_graph[left_child][0] == -1 and tree_graph[left_child][1] == -1 and tree_graph[right_child][0] == -1 and tree_graph[right_child][1] == -1:
res += 1
print(res) 第二题
给定一个字符串 s,问该字符串里有多少个长度大于 1的子串都是回文串?
strs = input()
def getSubList(s, left, right, tmp):
while left >= 0 and right < len(s) and s[left] == s[right]:
subString = s[left:right+1]
tmp.append(subString)
left -= 1
right += 1
if len(strs) == 1:
print(0)
else:
tmp = []
for i in range(len(strs)):
getSubList(strs, i, i, tmp)
getSubList(strs, i, i+1, tmp)
res = 0
for s in tmp:
if len(s) > 1:
res += 1
print(res)第三题
给定一个字符串,返回其中满足下列条件的最长字符串的长度:
'a','b','c','x','y','z'在字符串中都恰好出现了偶数次(0 也是偶数)
strs = input()
def helper(strs):
for i in range(len(strs), 0, -1):
for j in range(len(strs)-i+1):
subString = strs[j: j+i]
has_odd_zimu = True
for zimu in ['a','b','c','x','y','z']:
if subString.count(zimu) %2 != 0:
has_odd_zimu = False
break
if has_odd_zimu: return i
return 0
print(helper(strs))第四题
小易的幸运数字是 7,现有一个整数数组 nums,请找出并返回能被 7整除的子集合(即不要求是连续的子数组)的最大和,如果找不到则返回 -1。
arrs = list(map(int, input().strip().split()))
k = 7
n=len(arrs)
dp=[0]*7 # dp[i]表示余数是 i的最大数组中元素的和。初始化为0。模 7的余数范围是 0~6,故 dp数组长度为 7。
dp[arrs[0]%7] = arrs[0]
for i in range(1,n): # 迭代更新余数是 0-6的最大数组和的值。
dpc=dp.copy()
for k in dpc:
dp[(k+arrs[i])%7] = max(k+arrs[i], dp[(k+arrs[i])%7])
print(dp[0] if dp[0]!=0 else -1)#笔试题目##网易有道#
