串的模式匹配
BF算法
//3.3 串的模式匹配
//3.3.1 Brute-Force算法
//1. Brute-Force算法描述与实现
//返回当前串(目标串)中首个与模式串pattern匹配的子串序号,匹配失败时返回-1
public int indexOf(MyString pattern) {
return this.indexOf(pattern, 0);
}
//返回当前串(目标串)从begin开始首个与模式串pattern匹配的子串序号,若匹配失败返回-1。
//0≤begin<this.length()。对begin容错,若begin<0,从0开始;若begin序号越界,查找不成功。
//若pattern==null,抛出空对象异常。
public int indexOf(MyString pattern, int begin) {
int n = this.length(), m = pattern.length();
//返回两个串的长度
if (begin < 0) //对begin容错,若begin<0,从0开始
begin = 0;
if (n == 0 || n < m || begin >= n) //若目标串空、较短或begin越界,不需比较
return -1;
int i = begin, j = 0; //i、j分别为目标串和模式串当前字符下标
int count = 0;
//记载比较次数
while (i < n && j < m) {
count++;
if (this.charAt(i) == pattern.charAt(j)) //若当前两字符相等,则继续比较后续字符
{
System.out.print("t" + i + "=p" + j + ",");
i++;
j++;
} else //否则i、j回溯,进行下次匹配
{
System.out.println("t" + i + "!=p" + j + ",");
i = i - j + 1; //目标串下标i,退回到下个匹配子串序号
j = 0; //模式串下标j,退回到0
if (i > n - m) //若目标串剩余子串的长度<m,不再比较
break;
}
}
System.out.println("\tBF.count=" + count);
if (j == m) //匹配成功
return i - j; //返回匹配的子串序号
return -1; //匹配失败时返回-1
}
//《数据结构(Java版)(第5版)》,作者:叶核亚,2015年2月7日
//3.3 串的模式匹配
//3.3.1 Brute-Force算法
public class MyString_BF {
public static void main(String args[]) {
// MyString target=new MyString("aababcd"), pattern=new MyString("abcd"); //图3.11,匹配成功
// MyString target=new MyString("abcdabc"), pattern=new MyString("abcd"); //图3.12(a),匹配成功,最好情况
// MyString target=new MyString("aaaaa"), pattern=new MyString("aab"); //图3.12(b),最坏情况,匹配不成功
//习题解答
MyString target = new MyString("aaabaaaba"), pattern = new MyString("aaaa"); //习3-9(2)BF,习图3.4
System.out.println("\"" + target + "\".indexOf(\"" + pattern + "\")=" + target.indexOf(pattern));
}
}
/*
程序运行结果如下:
t0=p0,t1!=p1 //匹配4次
t1=p0,t2=p1,t3!=p2
t2!=p0
t3=p0,t4=p1,t5=p2,t6=p3, BF.count=10
"aababcd".indexOf("abcd")=3 //图3.11,匹配成功
t0=p0,t1=p1,t2=p2,t3=p3, BF.count=4 //匹配1次
"abcdabc".indexOf("abcd")=0 //图3.12(a),匹配成功,最好情况
t0=p0,t1=p1,t2!=p2 //匹配n-m+1=3次
t1=p0,t2=p1,t3!=p2
t2=p0,t3=p1,t4!=p2
BF.count=9 //比较(n-m+1)*m次,O(n*m)
"aaaaa".indexOf("aab")=-1 //图3.12(b),最坏情况,匹配不成功
t0=p0,t1=p1,t2=p2,t3!=p3 //习3-9(2)BF,匹配5次,习题解答图3.4
t1=p0,t2=p1,t3!=p2,
t2=p0,t3!=p1,
t3!=p0,
t4=p0,t5=p1,t6=p2,t7!=p3,
t5=p0,t6=p1,t7!=p2,
BF.count=17
"aaabaaaba".indexOf("aaaa")=-1
**/
//@author:Yeheya。2015-2-26
KMP算法
- next数组定义
j | 0 | 1 | 2 | 3 |
---|---|---|---|---|
模式串 | a | a | a | a |
k | -1 | 0 | 1 | 2 |
比较 | = | = | = | |
next[j] | -1 | -1 | -1 | -1 |