简体   繁体   中英

Longest palindrome in a string and it's length

I have a program that is supposed to go through a string identify possible palindromes, check if it is a palindrome and then return the length from palindromelength() or -1 if it is not, and print out the longest palindrome of the string. The program is compiling but the output is wrong.

This is my code

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int palindromelength(char *str, int i, int j){
    char *start = str;
    char *end  = str + j;
    while(start < end){
        if(*start != *end)
            return -1;
        start++;
        end--;
    }
    return j-i+1;
}
void ispalindrome(char *str){
    int length = 1, max = 1, start =0, i, j;
    for(i=0; i<= strlen(str) -2; i++){
        for(j= 1; j <= strlen(str)-1; j++){
            if(abs(i-j) > 1){
                length = palindromelength(str, i, j);
                if( length> max){
                    max = length;
                    start = i;
                }
            }
        }   
    }
    if(max > 1){
        printf("Largest palindrome is ");
        for( ; start <= j; start++){
            printf("%c", str[start]);
            start++;
        }
    }
    else
        printf("No palindromes in string.");
}

int main(void) {
    char a[50];
    char *a2;
    printf("Enter a string\n");
    scanf("%[^\n]", a);

    int length = strlen(a) + 1;
    a2 = (char*)malloc(length*sizeof(char));
    strcpy(a2, a);
    free (a2);

    char *a3 = &a;
    ispalindrome(a3);

    return 0;
}

I have tried the palindromelength() separately with a simple string, "aracecar". palindrimelength(a3, 0, 4) returns -1 so that is right, palindromelength(a3, 0, 3) returns 3 so that is right, but palindromelength(a3, 1, 7) returns -1, which is wrong. I double checked my function with other ones on stack overflow and it seems right, what could be the problem? As for the second function ispalindrome() is there a better way I could write that one? It just seems kind of messy right know.

I am a newbie, therefore I may not have yet learned some more advanced/sophisticated variations I could take to solve this.

I presume int i is the starting index of the string and int j is the ending index. If that is so, have a closer look at the first line of your palindromelength() function. Could the function ever start from somewhere other than index 0?

As for ways to do the ispalindrome() function, there are many algorithms out there to check whether or not an input is a palindrome, I would suggest having a look around and finding out different methods. If your way works, great! probably the cleanest way is to use recursion although that can take some thinking.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM