LintCode-13 字符串查找
描述
对于一个给定的 source 字符串和一个 target 字符串,你应该在 source 字符串中找出 target 字符串出现的第一个位置(从0开始)。如果不存在,则返回 -1。
样例
样例 1:
输入:
输出:
解释:
如果source里没有包含target的内容,返回-1
样例 2:
输入:
输出:
解释:
如果source里包含target的内容,返回target在source里第一次出现的位置
挑战
可用O(nm)算法,如果能用O(n)算法做出来就更好。(提示:KMP)
代码示例
采用改进的nextval的KMP算法实现
public class Solution {
public int strStr(String source, String target) {
char[] primary = source.toCharArray();
char[] pattern = target.toCharArray();
if(primary.length<=0&&pattern.length<=0){
return 0;
}
if(primary.length<=0){
return -1;
}
if(pattern.length<=0){
return 0;
}
int [] next = getNextval(pattern);
int i=0;
int j=0;
while(i<=primary.length-1&&j<=pattern.length-1){
if(j==-1||primary[i]==pattern[j]){
i++;
j++;
}
else{
j=next[j];
}
}
if(j<pattern.length){
return -1;
}
else{
return i-pattern.length;
}
}
public int[] getNextval(char[] pattern){
int [] nextval = new int[pattern.length];
nextval[0]=-1;
int i=0;
int j=-1;
while(i<pattern.length-1){
if(j==-1||pattern[i]==pattern[j]){
i++;
j++;
if(pattern[i]!=pattern[j]){
nextval[i]=j;
}
else {
nextval[i]=nextval[j];
}
}
else{
j=nextval[j];
}
}
return nextval;
}
public static void main(String[] args) {
Solution solution = new Solution();
String str1 = "abbabbbbcab";
String str2 = "babbb";
System.out.println(solution.strStr(str1,str2));
}
}
占用空间太多,目前还没有完善,后续如果有机会会去思考