Knuth Morris Pratt(KMP)는 왼쪽에서 오른쪽으로 문자를 확인하는 알고리즘입니다. 패턴에 하위 패턴이 두 개 이상 나타날 때 해당 속성을 사용하여 최악의 경우 시간 복잡성을 개선합니다.
KMP의 시간 복잡도는 O(n)입니다.
입력 및 출력
Input: Main String: “AAAABAAAAABBBAAAAB”, The pattern “AAAB” Output: Pattern found at location: 1 Pattern found at location: 7 Pattern found at location: 14
알고리즘
findPrefix(패턴, m, prefArray)
입력 - 패턴, 패턴의 길이 및 접두어 위치를 저장할 배열
출력 - 접두사가 있는 위치를 저장할 배열
Begin length := 0 prefArray[0] := 0 for all character index ‘i’ of pattern, do if pattern[i] = pattern[length], then increase length by 1 prefArray[i] := length else if length ≠ 0 then length := prefArray[length - 1] decrease i by 1 else prefArray[i] := 0 done End
kmpAlgorithm(텍스트, 패턴)
입력: 검색할 본문 및 패턴
출력 - 패턴이 발견된 위치
Begin n := size of text m := size of pattern call findPrefix(pattern, m, prefArray) while i < n, do if text[i] = pattern[j], then increase i and j by 1 if j = m, then print the location (i-j) as there is the pattern j := prefArray[j-1] else if i < n AND pattern[j] ≠ text[i] then if j ≠ 0 then j := prefArray[j - 1] else increase i by 1 done End
예시
#include<iostream>
using namespace std;
void findPrefix(string pattern, int m, int prefArray[]) {
int length = 0;
prefArray[0] = 0; //first place is always 0 as no prefix
for(int i = 1; i<m; i++) {
if(pattern[i] == pattern[length]) {
length++;
prefArray[i] = length;
}else {
if(length != 0) {
length = prefArray[length - 1];
i--; //decrease i to avoid effect of increasing after iteration
}else
prefArray[i] = 0;
}
}
}
void kmpPattSearch(string mainString, string pattern, int *locArray, int &loc) {
int n, m, i = 0, j = 0;
n = mainString.size();
m = pattern.size();
int prefixArray[m]; //prefix array as same size of pattern
findPrefix(pattern, m, prefixArray);
loc = 0;
while(i < n) {
if(mainString[i] == pattern[j]) {
i++; j++;
}
if(j == m) {
locArray[loc] = i-j; //item found at i-j position.
loc++;
j = prefixArray[j-1]; //get the prefix length from array
}else if(i < n && pattern[j] != mainString[i]) {
if(j != 0)
j = prefixArray[j-1];
else
i++;
}
}
}
int main() {
string str = "AAAABAAAAABBBAAAAB";
string patt = "AAAB";
int locationArray[str.size()];
int index;
kmpPattSearch(str, patt, locationArray, index);
for(int i = 0; i<index; i++) {
cout << "Pattern found at location: " <<locationArray[i] << endl;
}
} 출력
Pattern found at location: 1 Pattern found at location: 7 Pattern found at location: 14