class Solution {
/**
* Returns a index to the first occurrence of target in source,
* or -1 if target is not part of source.
* @param source string to be scanned.
* @param target string containing the sequence of characters to match.
*/
public int strStr(String source, String target) {
//write your code here
if(source == null || target == null)
return -1;
if(target.length() == 0)
return 0;
int[] next = new int[target.length()];
int m = 0, n = -1;
next[0] = -1;
while(m < target.length() - 1) {
if(n == -1 || target.charAt(m) == target.charAt(n)) {
m++;
n++;
next[m] = n;
} else {
n = next[n];
}
}
int i = 0, j = 0;
while(j < target.length() && i < source.length()) {
if(j == -1 || source.charAt(i) == target.charAt(j)) {
i++;
j++;
} else {
j = next[j];
}
}
if(j == target.length())
return i - j;
return -1;
}
}
再写String indexOf KMP算法
最新推荐文章于 2023-01-18 14:37:25 发布