(Java)LeetCode-28. Implement strStr()

Implement strStr().

Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.


这道题,首先我使用的是暴力查找法,用两个指针分别指向needle和haystack,然后移动比较即可,我自己写了一个版本,感觉写的不够好,然后就看了算法书上的版本,感觉同样是暴力查找,差距还是有的呀,于是贴上书上的代码,如下:


public class Solution {
    public int strStr(String haystack, String needle) {
        int M = needle.length();
		int N = haystack.length();
		
		for(int i = 0; i <= N-M; i++){
			int j;
			for(j = 0; j < M; j++){
				if(haystack.charAt(i+j) != needle.charAt(j))
					break;
			}
			if(j == M)
				return i;
		}
		return -1;
    }
}



然后我想尝试下KMP算法的,结果好慢呀,因为构造dfa数组耗费了很长时间,我估计这个算法适用在很长的迷惑性很大的字符串匹配中吧,代码如下,我这本书上的dfa数组是二维数组,我在网上看有些c++实现的是用一维数组的哎,不知道哪个更好,有关KMP查找算法我也是一知半解,知道了原理,不过让我自己把代码写出来还是不行,毕竟没有理解的那么透彻。好难。

public class Solution {
    public int strStr(String haystack, String needle) {
        if(needle.length() == 0){
            return 0;
        }
        KMP kmp = new KMP(needle);
		int result = kmp.search(haystack);
		return result;
    }
}

class KMP{
	private String pat;
	private int[][] dfa;
	public KMP(String pat){
		this.pat = pat;
		int M = pat.length();
		int R = 256;
		dfa = new int[R][M];
		dfa[pat.charAt(0)][0] = 1;
		for( int X = 0, j = 1; j < M; j++){
			for(int c = 0; c < R; c++){
				dfa[c][j] = dfa[c][X];
			}
			dfa[pat.charAt(j)][j] = j+1;
			X = dfa[pat.charAt(j)][X];
		}
	}
	
	public int search(String txt){
		int i,j,N = txt.length(), M = pat.length();
		for(i = 0, j = 0; i < N && j < M ; i++){
			j = dfa[txt.charAt(i)][j];
		}
		if(j == M)
			return i-M;
		else
			return -1;
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值