返回信息流在Leetcode上求解5. Longest Palindromic Substring时,出现了一个匪夷所思的bug,同样的测试用例,在RUN CODE的时候能通过,但是在SUBMIT的时候却会报错。
自己能力有限,来论坛请教各位前辈。
**************
Code如下:
**************
class Solution {
public:
string longestPalindrome(string s) {
int N =s.size()*2+1;
char chars[N];
cout << N << endl;
chars[0] = '#';
int i = 1;
for (char c: s){
chars[i++] = c;
chars[i++] = '#';
}
int len[N];
int center = 0;
int arm;
for (i=0; i<N; i++){
if (2*center-i >=0 && len[2*center-i]+i < center+len[center]){
len[i] = len[2*center-i];
cout << "1: ";
}
else{
cout << "2: ";
arm = 1;
if (i <= center+len[center])
arm += center+len[center]-i;
while (i-arm>=0 && i+arm<N && chars[i-arm]==chars[i+arm]){
arm ++;
}
len[i] = arm-1;
center = i;
}
cout << len[i] << endl;
}
int res = 0;
int record = 0;
for(i=0; i<N; i++){
int cur = len[i];
if (cur>res){
res = cur;
record = floor((i-len[i])/2);
}
}
cout << res << ' ' << record;
return s.substr(record, res);
}
};
***********
测试用例:"babad"
***********
RUN CODE时控制台输出如下:
Accepted:
11
2: 0
2: 1
2: 0
2: 3
1: 0
2: 3
1: 0
2: 1
2: 0
2: 1
2: 0
3 0
***********
SUBMIT 时控制台输出如下:
Runtime Error:
11
2: 443388417
2: 443388416
2: 443388415
2: 443388414
2: 443388413
2: 443388412
2: 443388411
2: 443388410
2: 443388409
2: 443388408
2: 443388407
443388417 -221694208
***********
这是一条镜像帖。来源:北邮人论坛 / cpp / #100424同步于 2020/11/17
该镜像源已超过 30 天没有更新,可能在源站已被删除。
CPP机器人发帖
[Leetcode] 请教一下最长回文子串
Easyer
2020/11/17镜像同步6 回复
订阅后,新回复会通过你的通知中心匿名送达。
6 条回复
学艺不精,确实是没有初始化的问题。memset一下就没这个问题了。
感谢回复!!!!
【 在 Jarvistj 的大作中提到: 】
: 看起来像数组没有初始化为0?不用vector最好memset一下?
保持初始化是个好习惯
【 在 Easyer 的大作中提到: 】
: 学艺不精,确实是没有初始化的问题。memset一下就没这个问题了。
: 感谢回复!!!!
: ............
感谢回复。初学C++,想到啥就用啥了。以后试试string。
【 在 sxfx 的大作中提到: 】
: 栈数组、栈变量,不初始化的都是随机值
: 以后刷题还是用string吧,char* 没string好用