查找char数组中最长的回文(代码差不多完成)

时间:2015-04-20 15:04:06

标签: c++ arrays char palindrome

我想在char数组中找到最长的回文。

这就是我的尝试:

#include <iostream>
#include <conio.h>
using namespace std;

bool valid(int s, int d, int n) {
    return s >= 0 && d < n;
}

char *calcPal(char cuv[], int stanga, int dreapta, int n) {
    char pal[50]={0};
    while (valid(stanga,dreapta,n))
        if(cuv[stanga] == cuv[dreapta])
        {
            if(strlen(pal))
                memmove(pal+1,pal,strlen(pal)+1);
            pal[0]=cuv[stanga];
            pal[strlen(pal)]=cuv[dreapta];
            stanga--;
            dreapta++;
        }
    return pal;

    // i'm returning the palindrome with my stanga and dreapta indexes
    // if it's not a palindrome, clearly it's not the longest so it's ok
}

char *v2(char cuv[]) {
    char max[10]={0};
    int n = strlen(cuv);
    int stanga, dreapta;
    char pal1[10]={0},pal2[10]={0};
    for (int i = 0; i < n-strlen(max); i++){
        stanga = i;
        dreapta = i+1;
        // this case is for even length words
        strcpy(pal1,calcPal(cuv, stanga, dreapta, n));
        // this case if for odd length word
        strcpy(pal2,calcPal(cuv, stanga-1, dreapta, n));
        if (strlen(pal1) > strlen(max))
            strcpy(max,pal1);
        if (strlen(pal2) > strlen(max))
            strcpy(max,pal2);
    }
    return max;
}

int main(int argc, const char * argv[]) {
    char cuv[] = "ce-miPlaceABBAwow";
    cout << v2(cuv);
    _getch();
    return 0;
}

此外,在有人问之前,不,我不想用字符串来解决它!

请告诉我这里我做错了什么!我的calcPal()函数没有返回正确的答案!谢谢!

2 个答案:

答案 0 :(得分:1)

在函数calcPal中,你声明了一个局部变量pal,你从函数返回它,这是非法的。

这可能会导致您的问题。

答案 1 :(得分:0)

dreapta只有stanga+1。你应该重温所有可能的组合:

for (int stanga=0;stanga<len;++stanga)
  for (int dreapta=s;dreapta<len;++dreapta) {
    strcpy(pal1,calcPal(cuv, stanga, dreapta, n));
    // this case if for odd length word
    strcpy(pal2,calcPal(cuv, stanga-1, dreapta, n));
    if (strlen(pal1) > strlen(max))
        strcpy(max,pal1);
    if (strlen(pal2) > strlen(max))
        strcpy(max,pal2);
  }
}