寻找最长回文

问题描述 投票:1回答:1

所以我想返回最长的回文,例如“ civic”返回“ civic”“ fawziizw”返回“ wziizw”那就是我尝试过的:

int ispalindrome (char str[],int start,int end) {
    int i=0;
    int j=0;
    int counter=0;
    for(i=start; i<strlen(str); i++) {
            if (str[i]==str[end-i]){
                counter++;
        }}
        if(counter==i){
        return counter;}
        else
            return 0;
    }
void longestPalindrome(char str[]) {
    int len = strlen(str);
    int i=0;
    int j=0;
    int start=0;
    Int end =0;
    int counter=0;
    int check=0;
    if (strlen(str)-1==1||strlen(str)-1==2) {
        printf("%s",str);
    } else {
        for (i=0; i<len; i++) {
            counter=0;
            for(j=len-1; j>=0; j--) {
                if(str[i]==str[j]) {
                    counter= ispalindrome(str,i,j);
                    if (counter>check&&counter>0) {
                        check=counter;
                        start=i;
                        end=j;
                    }
                }
            }
        }
        for(i=start; i<=end; i++) {
            printf("%c",str[i]);
        }
    }
}

因此它与诸如“公民”或“夫人”这样的回文式一起工作,我尝试使用“ fawziizw”,其返回值是“ f”,而不是“ wziizw”

c max palindrome
1个回答
1
投票

太近了!

在函数ispalindrome()中,您会错过最后一个字符,因为start可能不是0,并且来自i(> 0)的start将使end-i缺少字符串的结尾

int ispalindrome (char str[],int start,int end) {
    int i=0;
    int j=0;
    int counter=0;
    for(i=start; i<strlen(str); i++) {
            if (str[i]==str[end-i]){ // <===== end-i not ok if start>0
                counter++;
        }}
        if(counter==i){
        return counter;}
        else
            return 0; // better to leave whenever it's not a palindrome
    }

我建议使用一个简单的版本。我们将i用作0的计数器,因为start可能是>0,以便在这种情况下不会遗漏最后的字符

int ispalindrome (char str[],int start,int end) {
    for(int i=0 ; i < end-start ; i++) { 
          if (str[start+i] != str[end-i]){
                return 0; // <== return 0 if not a palindrome
        }}
     return end - start + 1; 
}

然后应该会更好。在下一个功能中,您可以更改

for(j=len-1; j>=0; j--)

to

for(j=len-1; j>i; j--)


以防万一,请使用longestPalindrome函数的较轻版本
void longestPalindrome(char str[]) {
    int len = strlen(str);
    int i,j;
    int tempstart=0;
    int tempend=0;
    int counter;
    int tempcounter=0;
     for (i=0; i<len; i++) {
          for(j=len-1; j>i; j--) { // >i
                counter= ispalindrome(str,i,j);
                if (counter>=tempcounter&&counter>0) {
                     tempcounter=counter;
                     tempstart=i;
                     tempend=j;
                }
          }
     }
     for(i=tempstart; i<=tempend; i++) {
          printf("%c",str[i]);
     }
     printf("\n");
}

基本相同。

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.