您的位置:首页 > 其它

leetcode 28. Implement strStr()

2017-05-19 19:21 369 查看
问题:

Implement strStr().

Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
采用KMP模式匹配算法:主要参考   http://blog.csdn.net/v_july_v/article/details/7041827 public class Solution {
public static int[] getNext(String sub){
int[] next=new int[sub.length()];
int k=-1,j=0;
next[0]=-1;
while(j<sub.length()-1){
if(k==-1||sub.charAt(k)==sub.charAt(j)){
k++;
j++;
next[j]=k;
}else{
k=next[k];
}
}
return next;
}
public int strStr(String haystack, String needle) {
if(needle.equals(""))return 0;
if(haystack.equals(""))return -1;
int i=0,j=0;
int[] next=getNext(needle);
while(i<haystack.length()&&j<needle.length()){
if(j==-1||haystack.charAt(i)==needle.charAt(j)){
i++;
j++;
}else{
j=next[j];
}
}
if(j==needle.length()){
return i-j;
}else return -1;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息