算法-数据结构 - leetcode 最长回文字符串,我的dp算法一直在本地测试通过,在leetcode上结果错误

查看:100
本文介绍了算法-数据结构 - leetcode 最长回文字符串,我的dp算法一直在本地测试通过,在leetcode上结果错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

以下是我的源代码:
`int dp1000 = {0};
char longestPalindrome(char s) {

int length = strlen(s);
int i = 0, j = 0;
char lstr[1000] = "";
int left = 0, maxLen = 1; 

if (!length) return "";
if (length == 1)  return s;

for (j = 0; j < length; j++) dp[j][j] = 1;

for (j = 0; j < length - 1; j++) {
    if (s[j] == s[j+1]) {
       dp[j][j+1] = 1;
       left = j;
       maxLen = 2;
    }
}
        
for (int len = 3; len <= length; len++) {  
    for (int i = 0; i < length - len + 1; i++) {  
      int j = i + len - 1;  
      if (s[i] == s[j] && dp[i+1][j-1]) {  
        dp[i][j] = 1;  
        left = i;  
        maxLen = len;  
      }  
    }  
 }  
 
 for ( i = left, j = 0; i < left + maxLen; i++,j++) {
     lstr[j] = s[i];
 }
//strncpy(lstr, s + left, maxLen);

return lstr;

}`

输入为"aaabaaaa" leetcode输出为"aaabaaaa"应该输出为"aaabaaa",在本地输出是aaabaaa

解决方案

你要相信同样的输入会产生同样的结果。如果出现了不同的结果,肯定是有一些条件被改变了。
看到这种情况应该就能猜到问题在之前的输入上。
试一下同时输入
"aaaabaaaa"
"aaabaaaa"
就能看到错误的结果了。

顺便说下lstr是局部变量,返回局部变量的地址是错误的。你不能保证函数执行完毕后它指向的数据仍然可用。

这篇关于算法-数据结构 - leetcode 最长回文字符串,我的dp算法一直在本地测试通过,在leetcode上结果错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆