Rabin-Karp는 보다 효율적인 방법으로 패턴을 찾기 위한 또 다른 패턴 검색 알고리즘입니다. 또한 창을 하나씩 이동하여 패턴을 확인하지만 모든 경우에 대해 모든 문자를 확인하지 않고 해시 값을 찾습니다. 해시 값이 일치하면 각 문자만 확인하려고 합니다. 이 절차는 알고리즘을 보다 효율적으로 만듭니다.
시간 복잡도는 O(m+n)이지만 최악의 경우 O(mn)입니다.
입력 및 출력
Input: Main String: “ABAAABCDBBABCDDEBCABC”, Pattern “ABC” Output: Pattern found at position: 4 Pattern found at position: 10 Pattern found at position: 18
알고리즘
rabinKarpSearch(text, pattern, prime)
입력 - 본문과 패턴입니다. 해시 위치 찾기의 또 다른 소수
출력 - 패턴이 발견된 위치
Begin patLen := pattern Length strLen := string Length patHash := 0 and strHash := 0, h := 1 maxChar := total number of characters in character set for index i of all character in pattern, do h := (h*maxChar) mod prime done for all character index i of pattern, do patHash := (maxChar*patHash + pattern[i]) mod prime strHash := (maxChar*strHash + text[i]) mod prime done for i := 0 to (strLen - patLen), do if patHash = strHash, then for charIndex := 0 to patLen -1, do if text[i+charIndex] ≠ pattern[charIndex], then break the loop done if charIndex = patLen, then print the location i as pattern found at i position. if i < (strLen - patLen), then strHash := (maxChar*(strHash – text[i]*h)+text[i+patLen]) mod prime, then if strHash < 0, then strHash := strHash + prime done End
예시
#include<iostream>
#define MAXCHAR 256
using namespace std;
void rabinKarpSearch(string mainString, string pattern, int prime, int array[], int *index) {
int patLen = pattern.size();
int strLen = mainString.size();
int charIndex, pattHash = 0, strHash = 0, h = 1;
for(int i = 0; i<patLen-1; i++) {
h = (h*MAXCHAR) % prime; //calculating h = {d^(M-1)} mod prime
}
for(int i = 0; i<patLen; i++) {
pattHash = (MAXCHAR*pattHash + pattern[i]) % prime; //pattern hash value
strHash = (MAXCHAR*strHash + mainString[i]) % prime; //hash for first window
}
for(int i = 0; i<=(strLen-patLen); i++) {
if(pattHash == strHash) { //when hash values are same check for matching
for(charIndex = 0; charIndex < patLen; charIndex++) {
if(mainString[i+charIndex] != pattern[charIndex])
break;
}
if(charIndex == patLen) { //the pattern is found
(*index)++;
array[(*index)] = i;
}
}
if(i < (strLen-patLen)) { //find hash value for next window
strHash = (MAXCHAR*(strHash - mainString[i]*h) + mainString[i+patLen])%prime;
if(strHash < 0) {
strHash += prime; //when hash value is negative, make it positive
}
}
}
}
int main() {
string mainString = "ABAAABCDBBABCDDEBCABC";
string pattern = "ABC";
int locArray[mainString.size()];
int prime = 101;
int index = -1;
rabinKarpSearch(mainString, pattern, prime, locArray, &index);
for(int i = 0; i <= index; i++) {
cout << "Pattern found at position: " << locArray[i]<<endl;
}
} 출력
Pattern found at position: 4 Pattern found at position: 10 Pattern found at position: 18