检查子数组是否为带指针的回文

check if sub-array is palindrome with pointers

我需要找到以原数组为中心的子数组,判断是否回文。之后我需要打印数组的起始索引 -1 和结束索引。

我试过了,但结果不是我所期望的。 你能指出我犯的任何错误吗?

#include <iostream>
using namespace std;

void print_sub_pals(int *nums,int length)
{

    for (int i = 0; i < (length / 2); ++i)
    {
        for (int j = length -1 ; j < (length/2); j--)
        {
            int start = *(nums + i);
            int end = *(nums + j);
            if ((start) == (end))
            {
                cout << start - 1 << endl;
                cout << end << endl;
            }
            else
            {
                cout << "-1" << endl;
            }
        }
    }
}



int main()
{
    int len = 7;
    int arr[7] = { 1, 2, 3, 4, 3, 6, 7 };
    print_sub_pals(arr, len);
}

我改变了第二个循环。现在至少进入了循环,我觉得还是得改一下。

void print_sub_pals(int *nums, int length)
{
    //example: length is 7,
    //i = 0, goes up to 3
    for (int i = 0; i < (length / 2); ++i)
    {
        //j starts from 6, goes down, it stops when it's not less than 3
        //for (int j = length - 1; j < (length / 2); j--) {//never gets here} 

        //j starts from 6, goes down, it stops when it's less than 3
        for (int j = length - 1; j >= (length / 2); j--)
        {
            int start = *(nums + i);
            int end = *(nums + j);
            if ((start) == (end))
            {
                cout << start - 1 << endl;
                cout << end << endl;
            }
            else
            {
                cout << "-1" << endl;
            }
        }
    }
}

我相信你的问题已经在上面通过第二个循环的修复解决了,但是一个建议:最好只使用你的第一个循环而不是 i。您可以将开始和结束定义更改为如下内容:

        int start = *(nums + i); 
        int end = *(nums + length - i - 1); 

通过此添加,您可以在 else 语句中添加 "break;" 以在数组违反回文条件时立即退出循环(如果这是您想要执行的操作)。

编辑:nums 是指针,所以 *(nums + i) for i = 0 是第一个元素。要比较真正的第一个和最后一个元素,您应该只打印 "start"。