递归地查找大海捞针的索引
Finding index of needle in haystack recursively.
我很快就要完成我的功能了。我需要获取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
当然,最简单的方法是定义一个静态变量来保持源字符串中的当前位置。但在这种情况下,我不认为这样的函数是"纯递归的"。
相关文章:
- 数组索引的值没有增加
- 芬威克树(BIT).找到具有给定累积频率的最小索引,单位为 O(logN)
- 查找最接近的大于当前数字的数字的索引
- 在C++中调整向量中的索引
- 重载元组索引运算符-C++
- 给定一个向量,如何找到该向量的所有子集和的原始索引
- 为std::string的某个索引赋值
- 并行用于C++17中数组索引范围内的循环
- 跟随整数索引列表的自定义类迭代器
- 如何在for循环中包含两个索引值的测试条件
- D3D11-将混合权重和索引传递到顶点着色器
- 将转换字符键入 int 以用作向量C++的索引
- 在 C++ 中访问数组负索引处的内存不会返回垃圾
- 如何为圆环创建索引
- 在子集化后将包含索引号的列表列表映射到标准索引序列
- 查找字符在两个索引之间出现的次数
- Azure Kinect 使用正文索引映射裁剪正文
- 如何查找哪个类对象位于数组的特定索引上(多态性)
- 数组索引重载错误
- 递归地查找大海捞针的索引