Python/strings/naive_string_search.py

33 lines
837 B
Python
Raw Normal View History

"""
this algorithm tries to find the pattern from every position of
the mainString if pattern is found from position i it add it to
the answer and does the same for position i+1
Complexity : O(n*m)
n=length of main string
m=length of pattern string
"""
2019-10-05 05:14:13 +00:00
def naivePatternSearch(mainString, pattern):
patLen = len(pattern)
strLen = len(mainString)
position = []
for i in range(strLen - patLen + 1):
match_found = True
for j in range(patLen):
2019-10-05 05:14:13 +00:00
if mainString[i + j] != pattern[j]:
match_found = False
break
if match_found:
position.append(i)
return position
2019-10-05 05:14:13 +00:00
mainString = "ABAAABCDBBABCDDEBCABC"
pattern = "ABC"
position = naivePatternSearch(mainString, pattern)
print("Pattern found in position ")
for x in position:
2019-10-05 05:14:13 +00:00
print(x)