我正在处理“代码信号”实践面试问题,我的代码通过了16/19测试,但由于超出了允许的时间限制,因此未能通过其余测试。
我尝试使用set()
而不是列表,但是count方法不起作用,并且由于我是python的新手,所以我不知道更好的选择。
def firstNotRepeatingCharacter(s):
list = []
num = '_'
for i in s:
list.append(i)
for i in list:
if list.count(i) <= 1:
num = i
return num
return num
如果您使用的是Python 3.7+,并且dict键按插入顺序排列,则可以使用collections.Counter
:
from collections import Counter
def firstNotRepeatingCharacter(s):
return next((char for char, count in Counter(s).items() if count == 1), '_')
[使用Python的早期版本,您可以使用collections.OrderedDict
来跟踪计数:
from collections import OrderedDict
def firstNotRepeatingCharacter(s):
counts = OrderedDict()
for char in s:
counts[char] = counts.get(char, 0) + 1
return next((char for char, count in counts.items() if count == 1), '_')
以便firstNotRepeatingCharacter('aababdcbcea')
返回:'d'