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

check if sub-array is palindrome with pointers

本文关键字:数组 指针 回文 是否 检查      更新时间:2023-10-16

我需要找到以原始数组中间为中心的子数组,并检查它是否是回文的。之后,我需要打印数组的开始索引-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);
}

我相信你的问题已经通过修复第二个循环解决了,但建议:最好只使用你的第一个循环而不是I。你可以将你的开始和结束定义更改为这样的东西:

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

通过此添加,您可以在else语句中添加一个"break;",以便在数组违反回文条件时立即退出循环(如果您想这样做的话)。

编辑:nums是指针,所以i=0的*(nums+i)是第一个元素。要比较真正的第一个元素和最后一个元素,只需打印"开始"即可。

我更改了第二个循环。现在至少它进入了循环,我认为你仍然需要改变它
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;
            }
        }
    }
}