【问题标题】:check if sub-array is palindrome with pointers检查子数组是否是带有指针的回文
【发布时间】:2015-03-29 12:57:27
【问题描述】:

我需要找到位于原始数组中间的子数组并检查它是否是回文。之后我需要打印数组的起始索引 -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 tried to do it but the outcome is not what I expected。相反,您能明确说明您的问题吗?
  • 第二个for循环条件j &lt; (length/2);不对
  • 抱歉没有把我的问题解释清楚。我试图找到子数组并检查它是否是回文,但输出没有打印任何内容。我想我的数组可能做错了。
  • 当您使用调试器时,哪一行导致了问题?变量的值是多少?代码流程是否正确?

标签: c++ pointers palindrome


【解决方案1】:

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

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

通过此添加,您可以添加“break;”当数组违反回文条件时,您的 else 语句立即退出循环(如果这是您想要做的)。

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

【讨论】:

  • 所以这只是比较一个数组和它的倒数。所有关于回文的花哨的谈话都是怎么回事......
【解决方案2】:

我改变了第二个循环。现在至少它进入了循环,我认为你仍然需要改变它。

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;
            }
        }
    }
}

【讨论】:

    猜你喜欢
    • 2011-06-07
    • 1970-01-01
    • 1970-01-01
    • 2017-10-23
    • 1970-01-01
    • 2021-03-06
    • 1970-01-01
    相关资源
    最近更新 更多