最近在看数据结构串的部分是,对串的匹配十分感兴趣,在严蔚敏老师的数据结构书上也讲到了对串的相关操作,而其中对串的匹配让人十分感兴趣。接下来就看看串的匹配算法。
1.朴素模式匹配算法 这里就不过多解释了
2.KMP模式算法匹配
具体的java代码如下
package nec.cn.stringComp;
public class KMPMatch
{
public static void main(String[] args)
{
String mainStr = "abcabcabdcabcabd";// 匹配串
String patternStr = "abcabd";// 模式串
int pLen = patternStr.length();
int next[] = new int[pLen];
caculate_next(next, patternStr);
for (int i = 0; i < pLen; i++)
{
System.out.println("计算得到next数组:");
System.out.print(next[i] + " ");
}
int find = match_KMP(mainStr, patternStr, next);
System.out.println("match position is " + find);
}
public static void caculate_next(int[] next, String p)
{
// 此处设定next数组的第0位和第1位的值为-1和0
next[0] = -1;
next[1] = 0;
int len = next.length;
for (int i = 2; i < len; i++)
{
if (p.charAt(i - 1) == p.charAt(next[i - 1]))
{
next[i] = next[i - 1] + 1;
} else
{
next[i] = 0;
}
}
}
public static int match_KMP(String m, String p, int[] next)
{
int mLen = m.length();
int pLen = p.length();
for (int i = 0, j = 0; i < mLen && j < pLen;)
{
if (m.charAt(i) == p.charAt(j))
{
// 如果i和j处的字符相等,则都加1
if (j == pLen - 1)
return i - j;
j++;
i++;
} else
{
// 不等的时候分两种情况讨论
if (-1 == next[j])
{
i++;
j = 0;
} else
j = next[j];
}
}
return -1;
}
}
对于其中的next[j]数组,详情可以查看严蔚敏老师的书。