码迷,mamicode.com
首页 > 编程语言 > 详细

Rolling Hash(Rabin-Karp 算法)

时间:2014-11-04 19:34:06      阅读:362      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   color   ar   os   java   for   sp   

// 闲言少许,直奔主题,我是宋鹏举。

import
java.io.PrintStream; public class RollingHash { private static final int R = 31; private int _hash; private int _rK; private CharSequence _c; private int _k; private int _offset; public RollingHash(int k) { if (k <= 0) { throw new IllegalArgumentException("k must be positive"); } this._k = k; this._rK = 1; for (int i = 1; i < k; i++) { this._rK *= 31; } } public void init(CharSequence c) { if (this._k > c.length()) { throw new IllegalArgumentException("k is greater then lenght of content"); } this._c = c; this._offset = 0; this._hash = 0; for (int i = 0; i < this._k; i++) { this._hash = (this._hash * 31 + this._c.charAt(i)); } } public boolean hasNext() { if (this._offset + this._k >= this._c.length()) { return false; } return true; } public int next() { if (this._offset + this._k >= this._c.length()) { throw new IllegalStateException("Past the end of content."); } int currentHash = this._hash; this._hash = ((this._hash - this._rK * this._c.charAt(this._offset)) * 31 + this._c.charAt(this._offset + this._k)); this._offset += 1; return currentHash; } public static void main(String[] args) { String text = "01234567890123456789012345678901234567890123456789testesteskdjfgdkfjghdkfjghdkfjghdkjgh"; int k = 20; RollingHash rh = new RollingHash(k); rh.init(text); for (int i = 0; rh.hasNext(); i++) { System.out.println("Hash " + i + ": " + rh.next()); } } }

 

Rolling Hash(Rabin-Karp 算法)

标签:style   blog   io   color   ar   os   java   for   sp   

原文地址:http://www.cnblogs.com/xyz2abc/p/4074270.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!