用于识别回文字符数组的递归函数

Recursive function for the recognition of the palindrome char arrays

本文关键字:递归函数 数组 字符 识别 回文 用于      更新时间:2023-10-16

我在大学里被分配了这个练习,但我不知道如何实现递归结构(代码中的"???")。 在 if 循环中,我应该将数组中的第一个字符与最后一个字符匹配并应用递归以到达中心字符,但我不知道如何设置代码。主函数代码完美编译。

#include <iostream>
using namespace std;
const int DIM = 8;
bool is_palindrome (char* first, char* last)
{
    if (first == last)
    {
        ???
    }
    else
     return false;
}
int main()
{
    char a[DIM] = {'i','n','g','e','g','n','i',''};
    char *first = &a[DIM] + 1;
    char *last = &a[DIM] -1;
    if (is_palindrome(first, last))
        cout << " the char array is palindrome ";
    else
            cout << " the char array is not palindrome ";
    return 0;
}

首先,您需要比较指针指向的值,而不是指针本身

if (*first == *last)

其次,您可以前进第一个并减少最后一个字符以移动一个字符:

// inside if
++first;
--last;

并使用指针的新值再次调用该函数:

return is_palindrome(first, last);

您还需要确保在实际获得回文时不会越过数组,因此将此检查添加到is_palindrome()

if (last < first) {
  return true;
}

此外,在main()中,您需要以这种方式初始化指针:

char* first = &a[0];
char* last = &[DIM-2];

您编写它的方式first已经指向数组,而last指向结尾'',这将与任何其他字符不匹配。

using namespace std;
const int DIM = 8;
bool is_palindrome ( char* first , char* last )
{
    if ( *first == '' )
    {
        return false;
    }
    else if ( first >= last )
    {
        return true;
    }
    else if ( *first == *last )
    {
        return is_palindrome(first + 1, last - 1);
    }
    else
    {
        return false;
    }
}
int main ()
{
    char a[DIM] = {'i','n','g','e','g','n','i',''};
    char *first = a;
    char *last = &a[DIM] - 2;
    if ( is_palindrome ( first , last ) )
    {
        cout << " the char array is palindrome ";
    }
    else
    {
        cout << " the char array is not palindrome ";
    }
    return 0;
}