这似乎非常简单,但如果我有精神障碍 我有一个字符串,其中只包含'_'和'x',我需要找到所有x序列的向后位置:
xxx___xxx___xxx
___x__xxx_xxx__
最快的方法是什么?我应该使用KMP还是BM,或者这是一种过度杀伤?
答案 0 :(得分:4)
您可以逐个字母地扫描字符串。这是python中的伪代码:
prev = ''
# enumerate(collection) enumerates collection elements along with their indices
# in the form of tuple (index, element)
# in python strings are collections of characters
for i, c in enumerate(string):
if c == 'x' and c != prev:
print "found x sequence at position %d" % i # (this prints out the index)
prev = c