网易笔试0928
第一题
题意
给一堆以空格分割的字符串,将这些字符串重新排列,在保证出现顺序的前提下字典序要尽可能的小。(如果不懂题目意思请看示例)
输入描述
第一行输入一行以空格分割的字符串
输出描述
输出去重后的字符串列表,在保证出现顺序的前提下字典序要尽可能的小。
示例
input: seo optimization seo tutorial seo tutorial output: optimization seo tutorial input: apple banana orange apple banana grape orange output: apple banana grape orange
思路
首先对输入进行去重,并记录该词首次出现位置first及最后出现位置last,然后对去重后的数据按字典序进行排序。
接下来对字典序的数据进行查询,保证元素的相对顺序和输入数据的相对顺序一致。
代码
自己写的python代码:
data = input().split()
first = {}
last = {}
temp = []
for i in range(len(data)):
if data[i] not in temp:
temp.append(data[i])
first[data[i]] = i
last[data[i]] = i
temp.sort()
idx = 0
while idx < len(temp) - 1:
if first[temp[idx]] > last[temp[idx+1]]:
re = temp[idx]
temp[idx] = temp[idx+1]
temp[idx+1] = re
idx -= 1
else:
idx += 1
print(temp)
代码可能存在bug
第二题
题意
给一个字符串x代表一个数字,x的长度小于等于一百万。求一个最小的y(可能超过long的表示范围且y必须大于等于0),使得x加上y是回文串。
输入描述
第一行输入x输出描述输出最小的y,使得x+y是回文串。
输出描述
输出最小的y,使得x+y是回文串。
示例
input: 96 output: 3 input: 3 output: 0
思路
取左边字段和右边字段,进行翻转比较。注意y必须大于0.
代码
data = '12345'
n = len(data)
if n != 1:
length = n // 2
left = data[:length]
left_re = left[::-1]
if n % 2 == 1:
right = data[length+1:]
right_re = right[::-1]
else:
right = data[length:]
right_re = right[::-1]
if int(left_re) > int(right):
y = int(left_re) - int(right)
elif int(left_re) < int(right):
if n % 2 == 1:
y = (int(right_re) - int(left)) * (10 ** (1 + length))
else:
y = (int(right_re) - int(left)) * (10 ** (len(left)))
elif int(left_re) == int(right):
y = 0
else:
y = 0
代码可能存在bug
查看7道真题和解析
