321
社区成员




找出最长回文串 (“回文串”是一个正读和反读都一样的字符串,比如“level”或者“noon”等等就是回文串)(测试用例仅做参考,我们会根据代码质量进行评分)
经典题目,不过代码量最少的,应该是马拉车算法(Manacher),嗯,老顾在每日一练以及CSDN周赛,不是以算法效率为目的,而是以不超时的最少代码为目的。
s = input()
p = '#'.join('^' + s + '$')
t = [0 for _ in range(len(p))]
for i in range(1,len(p) - 1):
while p[i - t[i] - 1] == p[i + t[i] + 1]:
t[i] += 1
mx = max(t)
pos = t.index(mx) // 2 - (mx + 1) // 2
print(s[pos:pos+mx])
js 里没有 max 方法,我们可以在 t[0] 位置记录一下最大长度,然后就没什么区别了
s = readline()
p = ('^' + s + '$').replace(/(?=.)/gi,'#').substr(1)
t = Array.from(new Array(p.length)).map(x => 0)
for (var i = 1 ; i < p.length - 1 ; i ++){
while (p.charAt(i - t[i] - 1) == p.charAt(i + t[i] + 1)){
t[i] ++;
t[0] = t[i] > t[0] ? t[i] : t[0];
}
}
pos = Math.floor(t.indexOf(t[0],1) / 2) - Math.floor((t[0] + 1) / 2)
print(s.substr(pos,t[0]))