旋轉(zhuǎn)hash(Rabin-Karp算法)實(shí)現(xiàn)字符串匹配

#include <bits/stdc++.h>

using namespace std;

/*旋轉(zhuǎn)hash(Rabin-Karp算法)實(shí)現(xiàn)字符串匹配

*基本原理:把每個(gè)字符當(dāng)做數(shù)字對(duì)待,這樣字符串就是一串?dāng)?shù)字,

? 把字符串比較操作轉(zhuǎn)化為數(shù)字比較操作*/

/*由于hash沖突存在,需要一個(gè)函數(shù)判斷兩個(gè)字符串確實(shí)相等*/

const int factor = 41;

int StrMatch(string source,string pattern){

int len1 = source.size();

int len2 = pattern.size();

assert(len2 <= len1);

int subHash = 0,curHash = 0;

for(auto i = 0;i < len2;++i){

subHash += (int)pattern[i] * factor;

curHash += (int)source[i] * factor;

}

/*先比較pat和src的第一個(gè)子串*/

if(curHash == subHash && source.substr(0,len2) == pattern)

return 0;

/*剩下子串開始遞推*/

for(auto i = 1; i <= len1 - len2;++i){

curHash = curHash - (int)source[i-1] * factor + (int)source[i + len2 - 1] * factor;

if(curHash == subHash && source.substr(i,len2) == pattern)

return i;

}

return -1;

}

int main(){

string s,p;

while(cin >> s >> p){

cout<<StrMatch(s,p)<<endl;

}

return 0;

}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容