前缀和回文递归问题如此接近工作,这里出了什么问题?多个测试用例返回 null
由于某种原因,我的解决方案返回 null 而不是存储在 's' 中的值。说明和代码如下:
给定一个字符串 s。考虑应用于该字符串的以下算法:
获取字符串的所有前缀,并选择它们之间最长的回文。 如果所选前缀至少包含两个字符,则从 s 中删除该前缀,并使用更新后的字符串返回到第一步。否则,以当前字符串 s 作为结果结束算法。 您的任务是实现上述算法并在应用于字符串时返回其结果。
测试用例 const s =“aaacodedoc”
预期输出:“”
另一个测试用例
const s = "阿巴" 预期输出:“b”
function solution(s) {
const prefixes =[]
if(s.length === 0){
return ""
}
if(s.length === 1){
return s
}
for(let i = 0; i < 1; i++){
for(let j = i; j < s.length; j++){
const substr = s.substring(i, j + 1)
prefixes.push(substr)
}
}
const palindromes = prefixes.filter(prefix => {
let reverse = prefix.split('').reverse().join('');
return prefix === reverse
})
let longest = palindromes.sort(
function (a, b) {
return b.length - a.length;
})[0];
if(longest.length >= 2){
s = s.substring(longest.length)
solution(s)
} else{
return s;
}
}
For some reason, my solution is returning null instead of the value that is stored in 's'. Instructions and code are below:
You are given a string s. Consider the following algorithm applied to this string:
Take all the prefixes of the string, and choose the longest palindrome between them.
If this chosen prefix contains at least two characters, cut this prefix from s and go back to the first step with the updated string. Otherwise, end the algorithm with the current string s as a result.
Your task is to implement the above algorithm and return its result when applied to string s.
test case
const s = "aaacodedoc"
expected output: ""
another test case
const s = "abbab"
expected output: "b"
function solution(s) {
const prefixes =[]
if(s.length === 0){
return ""
}
if(s.length === 1){
return s
}
for(let i = 0; i < 1; i++){
for(let j = i; j < s.length; j++){
const substr = s.substring(i, j + 1)
prefixes.push(substr)
}
}
const palindromes = prefixes.filter(prefix => {
let reverse = prefix.split('').reverse().join('');
return prefix === reverse
})
let longest = palindromes.sort(
function (a, b) {
return b.length - a.length;
})[0];
if(longest.length >= 2){
s = s.substring(longest.length)
solution(s)
} else{
return s;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Scott 的评论是正确的:
遇到了同样的问题,这只是递归调用中缺少返回语句。解释为什么您的一些测试用例通过了
len
len
len
len < 2.
。Scott's comment was correct:
Encountered this same issue and it was just a missing return statement on the recursive call. Explains why some of your test cases passed that checked for
len < 2
.