整数数组中最长的回文

Longest Palindrome in integer array

本文关键字:回文 数组 整数      更新时间:2023-10-16

我想在整数数组中找到最大的回文。我试着制作自己的算法,而不看网上的算法。但这是行不通的。我试着进行调试,但没能成功。

样本输入:

"1367611342142412431113424823782";

输出:113421424124311

void palindrome()
{
int max = 0;
int len;
int start;
int end;
int st=0,en=0;
bool palin = false;
for(int i=0;i<size;i++)
{
for(int j=size-1; j>=0;j--)
{
if(array[i] == array[j])
{
start = i;
end = j;
while(j==i+1 || j+1 == i || j == i )
{
if(array[i] == array[j])
{
i++; 
j--;
palin = true;
}
else
{
palin = false;
break;  
}
}
i= start;
j= end;
}
if(palin == true)
{
len = end - start;
if(len>max)
{
cout<<" "<<st<<" "<<en<<endl;
st=i;
en =j;
max = len;
}
}
}
}
cout<<endl;
cout<<st<<" "<<en<<endl;
ofstream file("output.txt");
for(int i=st;i<=en;i++)
{
file<<array[i];
}
}

有解决方案

#include <iostream>
#include <string>
struct Result
{   
int fromIndex, toIndex;
Result(int fromIndex, int toIndex){
this->fromIndex = fromIndex;
this->toIndex = toIndex;
}
int length(){
return toIndex - fromIndex;
}
};
bool isPalindrome(std::string &s, int left, int right){
while(left <= right){
if(s[left] != s[right]){
return false;
}
left ++;
right --;
}
return true;
}
std::string solve(std::string &s){
int startIndex = 0;
int toIndex = s.size() - 1;
Result result(0,0);
while(true){
if(isPalindrome(s, startIndex, toIndex)){
if(result.length() < (toIndex - startIndex)){
result.fromIndex = startIndex;
result.toIndex = toIndex;
}
}
toIndex --;
if(toIndex <= startIndex){
toIndex = s.size() - 1;
startIndex++;
}
if(startIndex == s.size() - 1){
break;
}
}
std::string str = "";
for (int i = result.fromIndex; i <= result.toIndex; ++i)
{
str += s[i];
}
return str;
}
int main()
{
std::string s = "1367611342142412431113424823782";
std::string result = solve(s);
std::cout << "Longest palindrome is: "<< result;
return 0;
}

您需要以更结构化的方式思考。首先将您的任务拆分为子任务。在这种情况下,有到个子任务:1.检查所有可能的组合2.检查这个组合是否是回文。每个任务都是另一个函数——这样更容易思考、阅读代码和调试。(如果您想将其写入文件,这是第三项任务!(

这是"检查所有可能的组合"的代码。如果一个数组是回文,我想你会发现如何检查它。

#include <iostream>
using namespace std;
bool isPalindrome(int* arr, int size);
bool findLargestPalindrome(int* arr, int size);
int main()
{
int arr[] = { 1,3,6,7,6,1,1,3,4,2,1,4,2,4,1,2,4,3,1,1,1,3,4,2,4,8,2,3,7,8,2 };
int arrSize = 31;
findLargestPalindrome(arr, arrSize);
}
bool findLargestPalindrome(int* arr, int size)
{
for (int testSize = size; testSize > 0; testSize--)
{
int startIndex = 0;
while (testSize + startIndex <= size)
{
int* arrayToTest = &(arr[startIndex]);
if (isPalindrome(arr, testSize))
{
//TODO: you found it - do with it whatever you want
return true;
}
startIndex++;
}
}
return false;
}
bool isPalindrome(int* arr, int size)
{
//TODO: your code for single palindrome
return false;
}