【发布时间】:2019-04-07 16:15:14
【问题描述】:
给定一个可能多次出现相同字符的字符串,返回与该字符串中任何指定字符最接近的相同字符。
给定字符串s 和n 的查询数。在每个查询中,您都会获得一个字符的索引a(其中0 <= a <= |s|),并且您需要打印壁橱相同字符的索引。如果有多个答案,请打印最小的一个。否则,打印-1。
例如,字符串s = 'youyouy',给定查询3:在索引0和6处有两个匹配的字符,每3个,我们选择最小的一个,即0。
这是我的计划: 我将字符串放入字典中,键是字符串中不同的字母,值是字母对应的索引。当给定查询时,在字典中找到对应的字母并返回最接近查询的值。
def closest(s, queries):
res = []
dict2={}
#dict2 - letter - indexs
for i in range(len(s)):
if s[i] not in dict2:
dict2[s[i]]=[i]
else:
dict2[s[i]].append(i)
for num in queries:
#closet- denotes closet letter index
closet = math.inf
#num is out of range , append -1
if num > (len(s)-1):
res.append(-1)
continue
#this is the only one letter, append -1
letter=s[num]
if len(dict2[letter])==1:
res.append(-1)
continue
#temp = list for that letters
temp=dict2[s[num]]
index=temp.index(num) . #in the list, letter index's index in list
if index==0:
closet=temp[1]
elif index==(len(temp)-1):
closet=temp[index-1]
else:
distance1=num-temp[index-1] . #left
distance2=temp[index+1]-num . #right
if distance1 <= distance2:
closet=temp[index-1]
else:
closet=temp[index+1]
if closet == math.inf:
res.append(-1)
else:
res.append(closet)
return res
我有两个运行时错误。我想知道您是否可以帮助我减少一些运行时间?
另外,我正在寻找其他建议!我用 Python 有一段时间了,正在找工作(大学应届毕业生)。 java通常比Python运行得快吗?我应该切换到Java吗?
【问题讨论】:
-
您的运行时错误是什么?
-
@HåkenLid 。他们只是告诉我由于运行时错误而终止,没有其他任何东西
-
@Robin 我不是说你要进一步缩短变量名;而是给他们起真正意味着某事的名字。你能发布
s和queries来测试函数吗? -
@Robin 可读名称不会立即解决您正在寻找的错误,但它们会帮助您和其他人了解您的想法和代码,从而使其他人更容易帮助您。让可理解的标识符成为您永远不会打破的习惯,即使是最脆弱的任务也不例外。
-
我很好奇:是什么让您得出它可能与速度有关的结论? “运行时错误”确实不指向执行时间,它指向您没有想出的输入值的错误。
标签: python arrays string algorithm dictionary