Rabin Karp Matching: String Matching
2015-05-19 07:24
295 查看
Rabin Karp matching:
Pseudo code:
Java code:
/** * Created with IntelliJ IDEA. * User: 1O1O * Date: 2015-03-31 * Time: 17:58 PM * :)~ * RABIN-KARP-MATCH:STRING-MATCH */ public class Main { public static void RABIN_KARP_MATCHER(String Text, String Pattern, int d, int q){ int n = Text.length(); int m = Pattern.length(); char[] textToChar = Text.toCharArray(); char[] patternToChar = Pattern.toCharArray(); int h = (int)Math.pow(d,m-1) % q; int p = 0; int[] t = new int[n-m+1]; t[0] = 0; for(int i=1; i<=m; i++){ p = (d*p+Character.digit(patternToChar[i-1],10))%q; t[0] = (d*t[0]+Character.digit(textToChar[i-1],10))%q; } for(int s=0; s<=n-m; s++){ if(p==t[s]){ int count = 0; for(int j=0; j<m; j++){ if(patternToChar[j]==textToChar[s+j]) count++; else break; } if(count==m){ System.out.println("Pattern occurs with shift: "+(s+1)); } } if(s<n-m){ int temp = t[s]-Character.digit(textToChar[s], 10)*h; temp = (temp<0)?temp+13:temp; t[s+1] = (d*temp+Character.digit(textToChar[s+m], 10))%q; } } } public static void main(String[] args) { String Text = "2359023141526739921"; String Pattern = "31415"; RABIN_KARP_MATCHER(Text, Pattern, 10, 13); } }
Output:
Pattern occurs with shift: 7
Reference:
From: 《INTRODUCTION TO ALGORITHMS》THIRD EDITION.
相关文章推荐
- String Matching -- Brute Force + Rabin-Karp + KMP
- Introduction to String Searching Algorithms--Rabin-Karp and Knuth-Morris-Pratt Algorithms [翻译]
- String matching using Rabin-Karp Algorithm
- Binary String Matching
- NYOJ-5 Binary String Matching
- Binary String Matching
- Binary String Matching
- Rabin-Karp-MATCHER字符串匹配算法; 一种效率还不错的匹配算法; 思想是关键.
- Aho-Corasick string matching in C#
- Rabin-Karp字符串查找算法
- hiho一下 第六十周 String Matching Content Length
- Binary String Matching(str.find())
- 南阳理工学院 Binary String Matching
- poj 1580 String Matching
- error: no matching function for call to 'std::basic_ifstream<char>::open(std::string&)
- NYOJ NO.5 Binary String Matching
- Binary String Matching 5 (简单KMP模板题)
- nyoj -5 Binary String Matching 【kmp】
- Binary String Matching 子串匹配
- 九度OJ 1094:String Matching(字符串匹配) (计数)