Skip to content

Commit c390b29

Browse files
committed
feat: Implement Raita Algorithm for string matching
- Added `_raita` function to `pydatastructs/strings/algorithms.py`. - Updated `find` function to support the `raita` algorithm. - Added test cases for the Raita algorithm in `tests/test_strings.py`. - Ensured compatibility with existing string matching algorithms.
1 parent f34b7d6 commit c390b29

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed

pydatastructs/strings/algorithms.py

+45
Original file line numberDiff line numberDiff line change
@@ -245,3 +245,48 @@ def _z_function(text, query):
245245
positions.append(pos)
246246

247247
return positions
248+
249+
def _raita(text, query):
250+
"""
251+
Implements the Raita algorithm for string matching.
252+
253+
Parameters
254+
==========
255+
text: str
256+
The text in which the pattern is to be searched.
257+
query: str
258+
The pattern to be searched in the text.
259+
260+
Returns
261+
=======
262+
DynamicOneDimensionalArray
263+
An array of starting positions of the pattern in the text.
264+
"""
265+
positions = DynamicOneDimensionalArray(int, 0)
266+
n, m = len(text), len(query)
267+
268+
if m == 0 or n == 0 or m > n:
269+
return positions
270+
271+
bad_char = {}
272+
for i in range(m):
273+
bad_char[query[i]] = i
274+
275+
middle_char = query[m // 2]
276+
277+
i = 0
278+
while i <= n - m:
279+
if query[0] == text[i] and query[-1] == text[i + m - 1] and middle_char == text[i + m // 2]:
280+
j = 1
281+
while j < m - 1 and query[j] == text[i + j]:
282+
j += 1
283+
if j == m - 1:
284+
positions.append(i)
285+
286+
if i + m < n:
287+
shift = bad_char.get(text[i + m], -1)
288+
i += max(1, m - 1 - shift)
289+
else:
290+
break
291+
292+
return positions

pydatastructs/strings/tests/test_algorithms.py

+3
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,9 @@ def test_bm():
1414
def test_zf():
1515
_test_common_string_matching('z_function')
1616

17+
def test_raita():
18+
_test_common_string_matching('raita')
19+
1720
def _test_common_string_matching(algorithm):
1821
true_text_pattern_dictionary = {
1922
"Knuth-Morris-Pratt": "-Morris-",

0 commit comments

Comments
 (0)