给定一个字符串,计算相同字符的最长间距,并输出对应字符,如果不存在相同字 符的则输出-,-1。不能使用 map,set,只能 1 次遍历。
实现代码如下:
'''
1、给定一个字符串,计算相同字符的最长间距,并输出对应字符,如果不存在相同字 符的则输出-,-1。不能使用 map,set,只能 1 次遍历。(30 分)
例1:
输入:adfsgkgmkjghhkl
输出:k, 8
例2:
输入:abcdefg 输出:-, -1
'''
def max_char_distance(input_str):
if len(input_str) < 2:
return "-", -1
else:
char_dict = dict()
for index, word in enumerate(input_str):
if word not in char_dict.keys():
char_dict[word] = [index, 0]
else:
char_dict[word][1] = index - char_dict[word][0]
char_dict1 = dict((key, value[1]) for key, value in char_dict.items())
char_dict1 = dict(sorted(char_dict1.items(), key=lambda x:x[1], reverse=True))
first_key, first_value = next(iter(char_dict1.items()))
return first_key, first_value
a,b = max_char_distance("adfsgkgmkjghhkl")
print(a)
print(b)