2025-02-25 17:04:18 -06:00

83 lines
1.6 KiB
Python

def kmp_table(S: str, W: str) -> list[int]:
T = [0] * len(S)
pos = 1
cnd = 0
while pos < len(W):
if W[pos] == W[cnd]:
cnd += 1
T[pos] = cnd
pos += 1
else:
if cnd != 0:
cnd = T[cnd - 1]
else:
T[pos] = 0
pos += 1
return T
# Returns a list of positions (indexes)
def kmp(S: str, W: str) -> list[int]:
if W not in S:
return []
j = 0
k = 0
T = kmp_table(S, W)
P = [] # Positions List
while j < len(S):
if W[k] == S[j]:
j += 1
k += 1
if k == len(W):
P.append(j - k)
k = T[k - 1]
else:
if k != 0:
k = T[k - 1]
else:
j += 1
return P
def find_search(S: str, W: str) -> list[int]:
pos = 0
i = 0
count = 0
positions = []
while (pos := S.find(W, i)) != -1:
i = pos + 1
positions.append(pos + 1)
count += 1
return positions
def main():
test_cases = int(input())
while (test_cases != 0):
test_case, token = input().split()
positions = kmp(test_case, token)
if len(positions) == 0:
print("Not Found", end='')
else:
print(len(positions))
for pos in positions:
if pos != positions[-1]:
print(f'{pos + 1} ', end='')
else:
print(f'{pos + 1}', end='')
if test_cases != 1:
print('\n')
test_cases -= 1
if __name__ == '__main__':
main()