2021.9.18美团笔试第4题 打印九键对应的字母
题目描述
如图所示的九键,输入2输出a,输入22输出b,若干次2,超过3次又从头开始
输入0 输出空格 ‘-’
输入-表示不执行操作,两次输入之前隔了一个 - 继续计数,如2-2输出b,隔了超过2个及其以上的 - 从头计数,如输入2–2输出aa
给定输入字符串如‘222233334-4-4—400555–666-0-0–0-077788888899999’
输出相应的字母 adig–so----rvw
代码
dic = {'2': ['a', 'b', 'c'], '3': ['d', 'e', 'f'], '4': ['g', 'h', 'i'],
'5': ['j', 'k', 's'], '6': ['m', 'n', 'o'], '7': ['p', 'q', 'r', 's'],
'8': ['t', 'u', 'v'], '9': ['w', 'x', 'y', 'z']}
str = '222233334-4-4---400555--666-0-0--0-077788888899999'
n = len(str)
res = ''
i = 0
non_op = 0
refresh = True
times = 0
cur = ' '
while i < n:
if str[i] == '0':
res += '-'
i += 1
elif str[i] == '-':
i += 1
else:
if refresh:
cur = str[i]
times = 0
non_op = 0
i = i + 1
while i < n and str[i] == cur:
times += 1
i += 1
while i < n and str[i] == '-':
non_op += 1
i += 1
if i == n or non_op > 1 or str[i] != cur:
res += dic[cur][times % (len(dic[cur]))]
refresh = True
non_op = 0
elif non_op <= 1:
refresh = False
else:
if str[i] != cur:
res += dic[cur][times % (len(dic[cur]))]
refresh = True
else:
non_op = 0
times += 1
i = i + 1
while i < n and str[i] == cur:
times += 1
i += 1
while i < n and str[i] == '-':
non_op += 1
i += 1
if non_op > 1:
res += dic[cur][times % (len(dic[cur]))]
refresh = True
print(res)