Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/55.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
解决leetcode 5问题时出现运行时错误。最长回文子串_C_Runtime - Fatal编程技术网

解决leetcode 5问题时出现运行时错误。最长回文子串

解决leetcode 5问题时出现运行时错误。最长回文子串,c,runtime,C,Runtime,我刚刚尝试使用dp方法来解决最长回文子串问题,这是源代码: #include<stdio.h> #include<string.h> #include<malloc.h> char* longestPalindrome(char *s) { int length=strlen(s); if(length == 0) { return ""; } if(length == 1) {

我刚刚尝试使用dp方法来解决最长回文子串问题,这是源代码:

#include<stdio.h>
#include<string.h>
#include<malloc.h>
char* longestPalindrome(char *s) 
{
    int length=strlen(s);
    if(length == 0)
    {
        return "";
    }
    if(length == 1)
    {
        return s;
    }
    int dp[length][length];
    int i,j;

    for(i=0;i<length;i++) 
    {
        for(j=0;j<length;j++)
        {
            if (i>=j)
            {
                dp[i][j]=1; 
            }
        }
    }

    int maxlen=1;
    int len_now=0;
    int start=0,fin=0;
    for(len_now=1;len_now<length;len_now++)
    {
        for(i=0;i+len_now<length;i++)
        {
            j=i+len_now;
            if(s[i] != s[j])
            {
                dp[i][j]=0;
            }
            else
            {
                dp[i][j]=dp[i+1][j-1];
                if(dp[i][j])
                {
                    if(len_now+1>maxlen)
                    {
                        maxlen=len_now+1;
                        start=i;
                        fin=j;
                    }
                }
            }
        }
    }

    /*char result[maxlen];
    strncpy(result, s+start,maxlen);
    result[maxlen]='\0';
    char *tao=result;
    return tao;*/
    //I firstly tried to use strncpy to copy the result into a new string, it works on my own computer(using mingw5), but it return NULL when I test it through leetcode, and then I find this solution as below:
    char *result = (char*)malloc(sizeof(char)*(maxlen));
    for(i = start,j = 0; j < maxlen; i++,j++)
    {
        result[j] = s[i];
    }
    result[j] = '\0';
    return result;
}
int main()
{
    char *s="abcba";
    char *p;
    p=longestPalindrome(s);
    printf("%s\n",p);
}
#包括
#包括
#包括
字符*最长回文(字符*s)
{
整数长度=strlen(s);
如果(长度==0)
{
返回“”;
}
如果(长度==1)
{
返回s;
}
int-dp[length][length];
int i,j;

对于(i=0;i您应该初始化
dp
正确。并引用运行时错误-否则您只是说“发生了我没有预料到的事情”变量
fin
在做什么?您设置了它,但从不使用它。您应该初始化
dp
正确。并引用运行时错误-否则您只是说“发生了我没有预料到的事情”变量
fin
在做什么?您设置了它,但从未使用过它。