Skip to content

Commit c494cfd

Browse files
committed
feat: multiple pattern kmp
1 parent 10d724f commit c494cfd

File tree

1 file changed

+42
-8
lines changed

1 file changed

+42
-8
lines changed

src/KMP.py

Lines changed: 42 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,47 +1,81 @@
11
class KMPMatcher:
22
def __init__(self, pattern):
3-
self.pattern = pattern
4-
self.lps = self.compute_lps(pattern)
3+
pass
54

65
# Buat longest prefix Suffix (LPS) array
76
def compute_lps(self, pattern):
7+
88
lps = [0] * len(pattern)
99
length = 0
1010

1111
i = 1
1212
while i < len(pattern):
13+
14+
# prefix suffix cocok
1315
if pattern[i] == pattern[length]:
1416
length += 1
1517
lps[i] = length
1618
i += 1
1719
else:
1820
if length != 0:
21+
# panjang prefix balik ke lps[length - 1]
1922
length = lps[length - 1]
2023
else:
2124
lps[i] = 0
2225
i += 1
2326
return lps
2427

2528
# cari semua posisi yang cocok, kalau tidak ada return array kosong
26-
def search(self, text):
29+
def search_pattern(self, text, pattern, case_sensitive=False):
2730
matches = []
28-
patternLen = len(self.pattern)
31+
patternLen = len(pattern)
2932
textLen = len(text)
3033

34+
if not case_sensitive:
35+
text = text.lower()
36+
pattern = pattern.lower()
37+
38+
lps = self.compute_lps(pattern)
39+
3140
i = 0
3241
j = 0
3342

3443
while i < textLen:
35-
if self.pattern[j] == text[i]:
44+
if pattern[j] == text[i]:
3645
i += 1
3746
j += 1
3847

48+
# pattern cocok ditemukan
3949
if j == patternLen:
4050
matches.append(i-j)
41-
j = self.lps[j-1]
42-
elif i < textLen and self.pattern[j] != text[i]:
51+
# posisi pattern dimulai dari index lps[j-1]
52+
j = lps[j-1]
53+
elif i < textLen and pattern[j] != text[i]:
4354
if j != 0:
44-
j = self.lps[j-1]
55+
j = lps[j-1]
4556
else:
4657
i += 1
4758
return matches
59+
60+
def search_multiple_pattern(self, text, patterns, case_sensitive=False):
61+
results = {}
62+
63+
if not text:
64+
return results
65+
66+
67+
if isinstance(patterns, str):
68+
patterns = [patterns]
69+
elif not isinstance(patterns, list):
70+
raise ValueError("Patterns must be a string or a list of strings.")
71+
72+
for pattern in patterns:
73+
if not isinstance(pattern, str):
74+
continue
75+
76+
pattern = pattern.strip()
77+
if pattern:
78+
matches = self.search_pattern(text, pattern, case_sensitive)
79+
results[pattern] = matches
80+
81+
return results

0 commit comments

Comments
 (0)