您的位置:首页 > 编程语言 > Java开发

(Java)LeetCode-28. Implement strStr()

2016-06-09 13:37 411 查看
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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: