Skip to content

Commit

Permalink
Added Boyer Moore search and manacher algorithms
Browse files Browse the repository at this point in the history
  • Loading branch information
krupalhp2907 committed Sep 25, 2020
1 parent 3bf0f20 commit 2442103
Show file tree
Hide file tree
Showing 2 changed files with 80 additions and 0 deletions.
45 changes: 45 additions & 0 deletions Strings/boyer_moore_search.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
"""
Pattern Finding.
"""


class BoyerMooreSearch:
def __init__(self, text, pattern):
self.text, self.pattern = text, pattern
self.textLen, self.patLen = len(text), len(pattern)

def match_in_pattern(self, char):
for i in range(self.patLen - 1, -1, -1):
if char == self.pattern[i]:
return i
return -1

def mismatch_in_text(self, currentPos):
for i in range(self.patLen - 1, -1, -1):
if self.pattern[i] != self.text[currentPos + i]:
return currentPos + i
return -1

def bad_character_heuristic(self):
positions = []
for i in range(self.textLen - self.patLen + 1):
mismatch_index = self.mismatch_in_text(i)
if mismatch_index == -1:
positions.append(i)
else:
match_index = self.match_in_pattern(self.text[mismatch_index])
i = (mismatch_index - match_index)
return positions


text = "ABAABA"
pattern = "AB"
bms = BoyerMooreSearch(text, pattern)
positions = bms.bad_character_heuristic()

if len(positions) == 0:
print("No match found")
else:
print("Pattern found in following positions: ")
print(positions)
35 changes: 35 additions & 0 deletions Strings/manacher.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
def palindromic_length(center, diff, string):
if (center - diff == -1 or center + diff == len(string)
or string[center - diff] != string[center + diff]):
return 0
return 1 + palindromic_length(center, diff + 1, string)


def palindromic_string(input_string):
max_length = 0

new_input_string = ""
output_string = ""

for i in input_string[:len(input_string) - 1]:
new_input_string += i + "|"
new_input_string += input_string[-1]

for i in range(len(new_input_string)):

length = palindromic_length(i, 1, new_input_string)

if max_length < length:
max_length = length
start = i

for i in new_input_string[start - max_length:start + max_length + 1]:
if i != "|":
output_string += i

return output_string


if __name__ == "__main__":
n = input()
print(palindromic_string(n))

0 comments on commit 2442103

Please sign in to comment.