简体   繁体   English

有人可以改进Java中indexOf的递归实现吗?

[英]Can someone improve the recursive implementation of indexOf in Java?

I've been working on a Java summer assignment and there was a problem on recursively implementing the indexOf method in Java. 我一直致力于Java夏季任务,并且在Java中递归实现indexOf方法存在问题。 Here is what I have so far: 这是我到目前为止:

public int rIndexOf(char ch, int fromPos)
{
    int charPos = fromPos;

    if (charPos >= myString.length() || myString.equals(""))
        return -1;
    else if (myString.charAt(charPos) == ch)
        return charPos;
    else
        return charPos + rIndexOf(ch, charPos + 1);
}

I seem to get values that are completely wrong, so I can only imagine it's a problem with incrementation or counting, but doesn't my code increment charPos by +1 each time? 我似乎得到了完全错误的值,所以我只能想象它是增量或计数的问题,但是我的代码每次都不会将charPos增加+1吗? Or does it have to do with ASCII values of characters? 或者它与字符的ASCII值有关?

Also I was wondering if the line "charPos = fromPos" was necessary at all. 此外,我想知道是否有必要使用“charPos = fromPos”这一行。 Could I have just used fromPos throughout my code or would that violate the "pass-by reference not value" thing? 我可以在整个代码中使用fromPos,还是会违反“传递引用而非价值”的事情?

You could absolutely have used fromPos all the way through your code. 绝对可以在代码中使用fromPos Java never passed by reference, and you're not even changing the value of charPos anyway. Java从未通过引用传递,您甚至无法改变charPos的值。

It's unclear why your final return statement adds charPos to the return value of the recursive call. 目前还不清楚为什么你的最终return语句 charPos 添加到递归调用的返回值。 Why isn't it just: 为什么不呢:

return rIndexOf(ch, charPos + 1);

? After all, suppose it finds it at position 3 - that's going to return 3, so you don't want to add 2 to the 3 in the previous call, then add 1 to the 5 and end up with 6... 毕竟,假设它在第3位找到它 - 那将返回3,所以你不想在前一次调用中将3添加到3,然后在5中加1,最后以6 ...

This line: 这一行:

return charPos + rIndexOf(ch, charPos + 1);

is flawed. 是有缺陷的。 Let's say myString is "the sun" and you call rIndexOf(' ', 0); 假设myString是“太阳”,你调用rIndexOf(' ', 0); Then you end up with: 然后你最终得到:

0 + 1 + 2 + 3 instead of 3. Since charPos is incremented each time and you add it to itself. 0 + 1 + 2 + 3而不是3.因为charPos每次都会递增并将其添加到自身。 You should just change that line to: 您应该将该行更改为:

return rIndexOf(ch, charPos + 1);

your last line is wrong, try this? 你的最后一行是错的,试试这个?

return rIndexOf(ch, charPos + 1)

also, this will create a huge stack in memory, not very efficient. 另外,这将在内存中创建一个巨大的堆栈,效率不高。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM