递归地查找大海捞针的索引

Finding index of needle in haystack recursively.

本文关键字:索引 大海捞针 查找 递归      更新时间:2023-10-16

我很快就要完成我的功能了。我需要获取2个字符串,并在字符串1中返回字符串2的索引。我知道有一个find函数,但我不能使用它。它还必须用递归编程来完成。

我有以下内容。

int index_of(string haystack, string needle) {
    int index = 0;
    string test = haystack.substr(index, needle.length());
    if (test == needle) {
        return index;
    }
    else {
        return 1 + index_of(haystack.substr(1), needle);
    }
}

它返回了大海捞针的索引,没问题,但有两件事我想不出来。

1) 如果针不在干草堆里,那么它需要返回-1。我已经这样做了,所以最后如果它不存在,它会返回-1,但因为它是递归的,所以它会添加其他返回1的次数。我不知道如何在最后只返回一个值而不添加所有其他实例。

2) 我想在其中使用一个helper函数,但我也不知道如何做到这一点。

谢谢你的帮助!

通常,您希望返回未掺杂的递归函数的值。在您的情况下,这是:

return 1 + index_of(some_parameters);

应该是这样的:

return index_of(some_parameters);

现在,您只需要选择参数,这样您就可以跟踪索引,直到您需要返回它,或者-1。

一个这样的函数可能有构造函数:

index_of(string haystack, string needle, int index);

这里有一个演示程序,展示了如何实现该函数。

#include <iostream>
#include <string>
std::string::size_type index_of( std::string haystack, const std::string &needle ) 
{
    if ( haystack.size() < needle.size() ) return std::string::npos;
    if ( haystack.compare( 0, needle.size(), needle ) == 0 ) return 0;
    std::string::size_type index;
    return ( index = index_of( haystack.substr( 1 ), needle ) ) == std::string::npos ? index : ++index; 
}
int main()
{
    std::string haystack( "asdfghjkl" );
    std::string needle( "gh" );
    std::string::size_type index = index_of( haystack, needle );
    if ( index != std::string::npos )
    {
        std::cout << "string "" << needle 
                  << "" is found in string "" << haystack 
                  << "" at position " << index
                  << std::endl;
    }
    else
    {
        std::cout << "string "" << needle 
                  << "" is not found in string "" << haystack << """
                  << std::endl;
    }
}

其输出为

string "gh" is found in string "asdfghjkl" at position 4

当然,最简单的方法是定义一个静态变量来保持源字符串中的当前位置。但在这种情况下,我不认为这样的函数是"纯递归的"。