Rabin Karp Algorithms Rabin Karp Algorithms A Rabin
Rabin Karp Algorithms
Rabin Karp Algorithms • 波動拳 ↓ → + A
Rabin Karp Algorithms • 昇龍拳 →↓ → + A
Rabin Karp Algorithms
KMP Algorithms • fail function diagram(圖例) • Ex: Sq = abcwerabc • 則failure[q] = ? • 以本例的話 failure[q] = 2 • 因為Sq的prefix最長S 2與後面Sq的suffix相等 • 雖然S 1也符合 但是S 2才是最長的
KMP Algorithms
KMP Algorithms • 程式碼實現=> • Part 1 計算目標字串自己的prefix跟suffix的 關係 (Failure function) • Part 2 利用Failure function去比對需要比對 的字串
KMP Algorithms • Failure Function的實現 • 1. 成功比對 存入Failure Function
KMP Algorithms • 程式碼 (fail function) fail[0] = -1; for(int i = 1, j = -1; i < Sub. size(); i++) { while(j >= 0 && Sub[i] != Sub[j+1]) j = failure[j]; //避免重複比對 if(Sub[i] == Sub[j+1]) j++; //比對成功 failure[i] = j; //紀錄failure function }
KMP Algorithms • 程式碼 (String matching KMP) for(int i = 0, j = -1; i < T. size(); i++) { while(j >= 0 && T[i] != Sub[j+1]) j = failure[j]; //避免重複 比對 if(T[i] == Sub[j+1]) j++; //比對成功 if(j == S. size()-1) //找到了目標字串 { cnt++; //找到了一次 j = failure[j]; } }
KMP Algorithms
好題目 • 出處 ACM UVA Contest Problem Set 11475 – • Extend to Palindrome • 網址 http: //uva. onlinejudge. org/index. php? optio n=com_onlinejudge&Itemid=8&category=26 &page=show_problem&problem=2470
好題目 • 程式參考解答 個人網誌網址: • http: //robertanders. pixnet. net/blog/post/27 122820
建議閱讀 • Introductions to algorithms 2/e page. 907 - page. 932 (如果自己覺得自習可以的話)
- Slides: 39