java 字符串 高效_java – 以高效的方式搜索字符串的流

我对Knuth Morris Pratt算法进行了部分搜索的几个更改。由于实际的比较位置总是小于或等于下一个,因此不需要额外的存储器。带有Makefile的代码也可以在

github上使用,它是用Haxe编写的,以便同时定位多种编程语言,包括Java。

class StreamOrientedKnuthMorrisPratt {

var m: Int;

var i: Int;

var ss:

var table: Array;

public function new(ss: String) {

this.ss = ss;

this.buildTable(this.ss);

}

public function begin() : Void {

this.m = 0;

this.i = 0;

}

public function partialSearch(s: String) : Int {

var offset = this.m + this.i;

while(this.m + this.i - offset < s.length) {

if(this.ss.substr(this.i, 1) == s.substr(this.m + this.i - offset,1)) {

if(this.i == this.ss.length - 1) {

return this.m;

}

this.i += 1;

} else {

this.m += this.i - this.table[this.i];

if(this.table[this.i] > -1)

this.i = this.table[this.i];

else

this.i = 0;

}

}

return -1;

}

private function buildTable(ss: String) : Void {

var pos = 2;

var cnd = 0;

this.table = new Array();

if(ss.length > 2)

this.table.insert(ss.length, 0);

else

this.table.insert(2, 0);

this.table[0] = -1;

this.table[1] = 0;

while(pos < ss.length) {

if(ss.substr(pos-1,1) == ss.substr(cnd, 1))

{

cnd += 1;

this.table[pos] = cnd;

pos += 1;

} else if(cnd > 0) {

cnd = this.table[cnd];

} else {

this.table[pos] = 0;

pos += 1;

}

}

}

public static function main() {

var KMP = new StreamOrientedKnuthMorrisPratt("aa");

KMP.begin();

trace(KMP.partialSearch("ccaabb"));

KMP.begin();

trace(KMP.partialSearch("ccarbb"));

trace(KMP.partialSearch("fgaabb"));

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值