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

[Leetcode] Implement strStr() (Java)

2013-12-28 15:07 441 查看
Implement strStr().

Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.

比较字符串,查找haystack中是否包含needle,如果包含则返回haystack中首先出现needle的指针,如果不包含则返回null

KMP算法,over[]代表覆盖度,从-1开始记,n代表 (n+1)个与模式串开头重复数

public class ImplementstrStr {
public String strStr(String haystack, String needle) {
if(haystack==null||needle==null||needle.length()>haystack.length())
return null;
if(needle.length()<1)
return haystack;
int[] over = new int[needle.length()];
over[0]=-1;
int preover;
for(int i=1;i<needle.length();i++){
preover = over[i-1];
while(preover>=0&&needle.charAt(i)!=needle.charAt(preover+1)){
preover = over[preover];
}
if(needle.charAt(i)==needle.charAt(preover+1))
over[i]=preover+1;
else
over[i]=-1;
}
int i=0,j=0;
while(i<haystack.length()&&j<needle.length()){
if(haystack.charAt(i)==needle.charAt(j)){
i++;
j++;
}else if(j==0){
i++;
}else {
j=over[j-1]+1;
}
}
if(j==needle.length())
return haystack.substring(i-j);
return null;
}
public static void main(String[] args) {
String haystack = "ababab135ab";
String needle = "ab1";
System.err.println(new ImplementstrStr().strStr(haystack, needle));
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: