用于反向查找的递归函数

Recursive function to reverse find

本文关键字:递归函数 查找 用于      更新时间:2023-10-16

char是递归函数。它不应该有任何l

这里有一个非常直接的递归实现。遗憾的是,它并不是尾递归的。

全面实施:

char *rfind(char* str, char ch) { 
     if (*str == '')
         return NULL; 
     char * pos = rfind(str + 1, ch);
     if (pos != NULL)
         return pos;
     if (*str == ch)
         return str;
     return NULL;
}

基本情况:str是一个由零个字符组成的字符串:

     if (*str == '')
         return NULL; 

递归调用:

     char * pos = rfind(str + 1, ch);

确定我们想要的是字符串剩余部分的结果,还是当前位置:

     if (pos != NULL)
         return pos;
     if (*str == ch)
         return str;
     return NULL;
递归不使用循环。

因此,如果你的函数名为rfind(…),那么在rfind中,你必须完成以下三项:

  • terminate withfind—确定您已经到达str的开头,然后使用nullptr 退出

  • 使用find终止--识别str中某个位置的"ch",然后退出并返回位置(char*)

  • 继续搜索——通过递归调用rfind(…),并返回递归调用返回的值。


编辑-只是为了好玩,这里有一个3参数的rfind,我认为它更可读

注意:没有循环,两种情况都退出,还有尾部递归。

// find _last_ occurrance of ch in str, starting at indx
char*  rfind(char*  str,  char ch, int indx)
{
   // Req 1: terminate when not found, return nullptr
   if(indx < 0)       return (nullptr);  
   // Req 2: terminate when found, return char*
   if(ch == str[indx]) return(&str[indx]) 
   // Req 3: continue search, return search results
   return ( rfind (str, ch, (indx-1)) );    // keep looking
}

〔removed-3参数rfind用法〕


编辑-为了完成这个版本,我提供以下内容。结果包括

a) 2参数rfind,

b) 尾部递归

c) 一些测试代码

我以普通读者的形式介绍以下内容。您将不得不添加前向声明或适当地重新安排代码以进行编译。

test_rfind()的用法:

请注意,test_rfind()有两个参数,它们被传递到rfind()中

int t122()
{
    char str[] = "t123abcdefg*o4";
    size_t strSize = strlen(str);
    std::cout << "n       strSize = " << strSize << "            " << (void*)str
              << "n       01234567890123" << std::endl;
    for (size_t i = 0; i < strSize; ++i) {
       test_rfind(str, str[i]);
    }
    test_rfind(str, 'z');
    test_rfind(str, '0');  // digit '0'
    test_rfind(str, 'K');
    // ...
 }

test_rfind调用rfind(),并筛选出空str和空tgt,为测试用户提供反馈:

void test_rfind(char* str, char tgt)
{
   do // not part of the recursion, not really a loop, just a test simplification
   {
      if (0 == str) { std::cout << "       str is null " << std::endl;  break; }
      // ===================================================================
      char* pos = rfind(str, tgt);  // 2 parameter invocation - see below
      // ===================================================================
      if (nullptr == pos) {
         std::cout << "rfind('" << std::setw(14) << str
                << "', '" << tgt << "') :           "
                   << "  char '" << tgt
                   << "' not found" << std::endl;
         break;
      }
      // else found
      std::cout << "rfind('" << std::setw(14) << str
                << "', '" << tgt << "') = "
                << (void*)pos
                << std::setw(20) << pos
                << "    last '"  << pos[0]
                << "' at indx: " << (pos - str) << std::endl;
   }while(0);
}

这是您需要的2个参数rfind()。

惊喜!它只是进行一些验证,然后使用现有的3个参数rfind()。

// two parameter
char*  rfind(char*  str,  char tgt)
{
   // pre-validation
   if (0 == str) return(nullptr); // one null check here, rather than 'inside' recursion
   // pre-validation - tbr: check range (0 <= char <= 127)
   // allow (0 == tgt): a char can be 0
   // now use the 'just for fun' 3 parameter rfind
   return ( rfind(str, tgt, strlen(str)) );  // use tail recursion
}

我发现,在递归的过程中,这种"中间步骤"处理了几个前(有时是后)验证。这样可以避免这些事情使实际的递归函数复杂化。

3参数rfind()在这个答案的开头附近,并且使用时没有改变。

你猜怎么着——它提供了一个通常必要的功能:查找字符串中的最后一个目标字符,但你可以在字符串中的任何地方开始搜索。这样,如果您的字符串有两个tgt字符-您可以使用2参数rfind()找到最后一个ch,然后使用第3个参数(而不是缩短str)找到该字符之前的tgt。

注意:当两个函数的签名是唯一的时,C++允许它们具有相同的标识符。因此,2参数和3参数版本都共享名称"rfind()"。

测试结果:

       strSize = 14            0xbff8f4bd
       01234567890123
rfind('t123abcdefg*o4', 't') = 0xbff8f4bd      t123abcdefg*o4    last 't' at indx: 0
rfind('t123abcdefg*o4', '1') = 0xbff8f4be       123abcdefg*o4    last '1' at indx: 1
rfind('t123abcdefg*o4', '2') = 0xbff8f4bf        23abcdefg*o4    last '2' at indx: 2
rfind('t123abcdefg*o4', '3') = 0xbff8f4c0         3abcdefg*o4    last '3' at indx: 3
rfind('t123abcdefg*o4', 'a') = 0xbff8f4c1          abcdefg*o4    last 'a' at indx: 4
rfind('t123abcdefg*o4', 'b') = 0xbff8f4c2           bcdefg*o4    last 'b' at indx: 5
rfind('t123abcdefg*o4', 'c') = 0xbff8f4c3            cdefg*o4    last 'c' at indx: 6
rfind('t123abcdefg*o4', 'd') = 0xbff8f4c4             defg*o4    last 'd' at indx: 7
rfind('t123abcdefg*o4', 'e') = 0xbff8f4c5              efg*o4    last 'e' at indx: 8
rfind('t123abcdefg*o4', 'f') = 0xbff8f4c6               fg*o4    last 'f' at indx: 9
rfind('t123abcdefg*o4', 'g') = 0xbff8f4c7                g*o4    last 'g' at indx: 10
rfind('t123abcdefg*o4', '*') = 0xbff8f4c8                 *o4    last '*' at indx: 11
rfind('t123abcdefg*o4', 'o') = 0xbff8f4c9                  o4    last 'o' at indx: 12
rfind('t123abcdefg*o4', '4') = 0xbff8f4ca                   4    last '4' at indx: 13
rfind('t123abcdefg*o4', 'z') :             char 'z' not found
rfind('t123abcdefg*o4', '0') :             char '0' not found
rfind('t123abcdefg*o4', 'K') :             char 'K' not found

最近,我对递归代码中的-O3优化印象深刻。

  • 在一些尾部递归中,编译器完全删除了递归调用和返回,作为没有发生堆栈溢出的证据,其中当以-O0编译时,可执行文件总是崩溃。

  • 在至少一个可重复测试中,得到的完全优化递归实现比相应的完全优化循环实现快50%。