[英]Custom indexOf without String methods
I created my own indexOf
function. 我创建了自己的
indexOf
函数。 I was wondering if anyone could help me come up with a way to make it more efficient. 我想知道是否有人可以帮助我提出提高效率的方法。 I am practicing for interviews so the catch is that I cannot use any String methods.
我正在练习面试,所以要注意的是我不能使用任何String方法。 I believe the runtime of this method is O(n^2) with space of O(n).
我相信此方法的运行时间为O(n ^ 2),空间为O(n)。 Correct me if I am wrong.
如果我错了,请纠正我。
Also, I want to ensure the program runs safely and correctly, the only test case I can think of it the length comparison. 另外,我想确保程序安全正确地运行,这是我可以想到的唯一测试用例,即长度比较。
code: 码:
public static int myIndexOf(char[] str, char[] substr) {
int len = str.length;
int sublen = substr.length;
int count = 0;
if (sublen > len) {
return -1;
}
for (int i = 0; i < len - sublen + 1; i++) {
for (int j = 0; j < sublen; j++) {
if (str[j+i] == substr[j]) {
count++;
if (count == sublen) {
return i;
}
} else {
count = 0;
break;
}
}
}
return -1;
}
Try here for string searching algorithms: http://www-igm.univ-mlv.fr/~lecroq/string/ 在此处尝试使用字符串搜索算法: http : //www-igm.univ-mlv.fr/~lecroq/string/
And here for a way to test your implementation: http://junit.org/ 这里是测试实现的一种方法: http : //junit.org/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.