检查子数组是否为带指针的回文数组
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);
}
我相信你的问题已经通过修复第二个循环解决了,但建议:最好只使用你的第一个循环而不是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;
}
}
}
}
相关文章:
- 添加到数组指针
- C++语法差异:二维和一维数组(指针算术)
- 数组指针表示法C++(移动数组时)
- 复制后删除原始数组指针将前 3 个字节设置为 0
- C++访问指向结构的指针中的类数组指针
- C++编译时使用 constexpr 字符数组指针分配静态数组?
- std::flush可以用于将对象指针转换为其封闭数组指针吗
- 创建<int>对整数数组指针的矢量引用 (C++)
- 将 2D 数组指针传递给 C++ 中的函数
- 创建指针是否超过非数组指针的末尾,而不是从 C++17 中的一元运算符和未定义的行为派生?
- 队列数组指针 (C++)
- C++数组指针上的删除操作
- 对于循环不循环和检测字符数组 [指针和字符数组]
- 如何初始化数组指针对象
- 如何正确传递 2D 数组指针作为参数
- 从数组指针中获取怪异的数字
- 初始化std :: unique_ptr作为原始数组指针的初始化
- 将结构数组指针从C#传递到C
- STD :: Sort将数组指针设置为NULL
- C++数组指针错误无法将“int*”转换为“int**”