A strange error.There is one more " in my output.Why?


  • 0
    B
    char* longestPalindrome(char* s) {
    static char *a;
    int t[1000][1000]={0};
    int n=0;
    int begin=0;
    int max=1;
    while(s[n]!='\0')
    {
        n++;
    }
    for(int i=0;i<n;i++)
    {
        t[i][i]=1;
    }
    for(int i=0;i<n-1;i++)
    {
        if(s[i]==s[i+1])
        {
            t[i][i+1]=1;
            begin=i;
            max=2;
        }
    }
    for(int len=3;len<=n;len++)
    {
        for(int i=0;i<n-len+1;i++)
        {
            int j=i+len-1;
            if(s[i]==s[j]&&t[i+1][j-1]==1)
            {
                t[i][j]=1;
                begin=i;
                max=len;
            }
        }
    }
    a=(char *)malloc(max*sizeof(char));
    for(int i=0;i<max;i++)
    {
        a[i]=s[i+begin];
    }
    return a;
    

    }

    Input: "dddddddd"
    Output:"dddddddd""
    Expected:"dddddddd"

    why there is one more " in my output


  • 1

    I'd say you're lucky it doesn't cause a runtime error. You need to end your output string with a '\0' just like the input string. Otherwise the OJ of course doesn't know when to stop, and apparently there happens to be a '"' in memory after your output.


  • 0
    B

    But I use this case in testcase,the answer is right.Why?


  • 0

    Because you're even luckier there.


  • 0
    B

    What should I write? I change it to n=strlen(s),but it has the same error .


  • 0

    What I already told you: You need to end your output string with a '\0'.


  • 0
    B

    Thank you very much! I know what should I do! At the beginning I misunderstood what you mean.Now I understand.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.