字符串匹配的KMP算法

本文是字符串匹配的KMP算法实现:

kmp算法的介绍可以查看阮一峰的这篇博客:http://ruanyifeng.com/blog/2013/05/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm.html

 

package algorithm;

public class Kmp {
	private String totalStr;
	private String matchStr;
	// 部分匹配表
	private int[] matchTable;
	// 匹配结果
	private boolean result;
	// 匹配到的起始位置
	private int index;

	public Kmp(String totalStr, String matchStr) {
		this.totalStr = totalStr;
		this.matchStr = matchStr;
		this.matchTable = matchTable(matchStr);
		search(totalStr, matchStr, matchTable);
	}

	/**
	 * 计算部分匹配表
	 * */
	private int[] matchTable(String str) {
		if ("".equals(str) || null == str) {
			return null;
		} else {
			if (str.length() == 1) {
				matchTable = new int[0];
			} else {
				String[] prefix = null;
				String[] suffix = null;
				int matchNum = 0;
				matchTable = new int[str.length()];
				matchTable[0] = 0;
				for (int i = 1; i < str.length(); i++) {
					String newStr = str.substring(0, i + 1);
					prefix = new String[newStr.length() - 1];
					suffix = new String[newStr.length() - 1];
					for (int j = 0; j < newStr.length() - 1; j++) {
						prefix[j] = newStr.substring(0, j + 1);
						suffix[j] = newStr.substring(1 + j, newStr.length());
					}
					for (int j = 0; j < prefix.length; j++) {
						if (prefix[j].equals(suffix[prefix.length - j - 1])) {
							matchNum += prefix[j].length();
						}
					}
					matchTable[i] = matchNum;
					matchNum = 0;
				}
			}
		}
		return matchTable;
	}

	/**
	 * 查找字符串
	 * */
	private String search(String str, String s, int[] partMatch) {
		for (int i = 0; i < str.length(); i++) {
			for (int j = 0; j < s.length(); j++) {
				if (!str.substring(i, i + j + 1).equals(s.substring(0, j + 1))) {
					if (j == 0) {
						break;
					} else {
						int drift = j - partMatch[j - 1];
						i = i + drift - 1;
						break;
					}
				} else {
					if (j == s.length() - 1) {
						this.result = true;
						this.index = i;
						return null;
					}
				}
			}
		}
		this.result = false;
		this.index = -1;
		return null;
	}

	public boolean isResult() {
		return result;
	}

	public int getIndex() {
		return index;
	}

	public String getMatchStr() {
		return matchStr;
	}

	public void setMatchStr(String matchStr) {
		this.matchStr = matchStr;
	}

	public String getTotalStr() {
		return totalStr;
	}

}

以下是调用方法

 

 

public static void main(String[] args) {
		String str = "BBC ABCDAB ABCDABCDABDE";
		String s1 = "ABCDABD";
		String s2 = "BBA";
		Kmp kmp = new Kmp(str, s1);
		System.out.println(kmp.getIndex() + ":" + kmp.isResult());
		kmp = new Kmp(str, s2);
		System.out.println(kmp.getIndex() + ":" + kmp.isResult());
	}

 

个人博客:www.katts.cn

 

 

 

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值