Cải thiện bài viết
Lưu bài viết
Cải thiện bài viết
Lưu bài viết
Đọc
Examples:
Input: txt[] = "THIS IS A TEST TEXT" pat[] = "TEST" Output: Pattern found at index 10 Input: txt[] = "AABAACAADAABAABA" pat[] = "AABA" Output: Pattern found at index 0 Pattern found at index 9 Pattern found at index 12
Bàn luận
Python3
Cho một văn bản txt [0..n-1] và một mẫu pat [0..M-1], viết một tìm kiếm chức năng [char pat [], char txt []] in tất cả các lần xuất hiện của pat [] trong txt []. Bạn có thể giả sử rằng n> m. & Nbsp; ví dụ: & nbsp;
Tìm kiếm mẫu là một vấn đề quan trọng trong khoa học máy tính. Khi chúng tôi tìm kiếm một chuỗi trong tệp notepad/word hoặc trình duyệt hoặc cơ sở dữ liệu, các thuật toán tìm kiếm mẫu được sử dụng để hiển thị kết quả tìm kiếm. & Nbsp; & nbsp;
def
KMPSearch[pat, txt]:
M
__ len
[pat]
1
=
len
4
Found pattern at index 108
Các
Found pattern at index 104
=
9
def
0
9
def
4 def
5
def
6def
7 def
8=
__ KMPSearch[pat, txt]:
1
KMPSearch[pat, txt]:
2def
0304444 KMPSearch[pat, txt]:
6
KMPSearch[pat, txt]:
2
Found pattern at index 104
KMPSearch[pat, txt]:
4=
KMPSearch[pat, txt]:
6def
6def
7
Found pattern at index 104
=
__
7KMPSearch[pat, txt]:
2
9 M
0M
1M
2M
3M
44565
KMPSearch[pat, txt]:
2
Found pattern at index 104
=
=
0M
5KMPSearch[pat, txt]:
6Found pattern at index 100
def
6=
5 =
6=
7 =
8=
KMPSearch[pat, txt]:
1
KMPSearch[pat, txt]:
2[pat]
5len
6
KMPSearch[pat, txt]:
2def
7 len
3=
9
len
6len
7
Found pattern at index 104
=
=
0M
5KMPSearch[pat, txt]:
6Found pattern at index 100
len
7def
0304444 KMPSearch[pat, txt]:
6
09
9
11
def
03
len
=
9
def
0 KMPSearch[pat, txt]:
6
def
4
18
Các
def
4 def
5
def
6[pat]
5len
6
def
6def
7 def
8=
__ KMPSearch[pat, txt]:
1
KMPSearch[pat, txt]:
2def
0304444 KMPSearch[pat, txt]:
6
KMPSearch[pat, txt]:
2[pat]
5len
6
KMPSearch[pat, txt]:
2
Found pattern at index 104
KMPSearch[pat, txt]:
4=
KMPSearch[pat, txt]:
6KMPSearch[pat, txt]:
2def
7 len
3=
9
len
6len
7
Found pattern at index 104
=
=
0M
5KMPSearch[pat, txt]:
6Found pattern at index 100
len
7def
0304444 KMPSearch[pat, txt]:
6
77
Output:
Found pattern at index 10
def
03: O[m+n]
len
=
9: O[m]
def
0 KMPSearch[pat, txt]:
6