Skip to content

Commit d0370db

Browse files
fix(strings): avoid counting false matches in z-function search (#15302)
1 parent db01fc3 commit d0370db

1 file changed

Lines changed: 4 additions & 9 deletions

File tree

strings/z_function.py

Lines changed: 4 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -68,20 +68,15 @@ def find_pattern(pattern: str, input_str: str) -> int:
6868
4
6969
>>> find_pattern("xz", "zxxzxxz")
7070
2
71+
>>> find_pattern("aa", "a")
72+
0
7173
"""
72-
answer = 0
74+
pattern_length = len(pattern)
7375
# concatenate 'pattern' and 'input_str' and call z_function
7476
# with concatenated string
7577
z_result = z_function(pattern + input_str)
7678

77-
for val in z_result:
78-
# if value is greater then length of the pattern string
79-
# that means this index is starting position of substring
80-
# which is equal to pattern string
81-
if val >= len(pattern):
82-
answer += 1
83-
84-
return answer
79+
return sum(value >= pattern_length for value in z_result[pattern_length:])
8580

8681

8782
if __name__ == "__main__":

0 commit comments

Comments
 (0)