JavaScript回文字符串函数输出不符,如何修正以符合预期?
字符串挑战问题修正
字符串挑战要求
实现StringChallenge(str)函数,判断是否可通过移除1个或2个字符,生成长度至少为3的回文字符串,规则如下:
- 若输入本身是回文,返回字符串
"palindrome"; - 若可生成符合要求的回文,返回被移除的字符(按原字符串出现顺序,优先移除更早出现的字符,且需生成最长回文子串);
- 若无法生成,返回
"not possible"。
现有问题
当前实现的函数在测试用例StringChallenge("kjjjhjjj")时,预期输出为"k",但实际输出为"jjjhjjj",其他部分测试用例表现正常,需要修正函数使其输出符合预期。
现有代码
function StringChallenge(str) { if(str === str.split("").reverse().join("")) {return str;}; let result = ""; for (let i = 0; i < str.length; i++) { let items = str[i]; for (let j = i + 1; j < str.length; j++) { items += str[j]; if (items === items.split("").reverse().join("")) { if ( result.length < items.length) {result = items;} } } } return result.length < 3 ? "not possible" : result ; } console.log(StringChallenge("kjjjhjjj")); // 预期输出 "k" - 实际输出 "jjjhjjj" console.log(StringChallenge("ana")); // 预期输出 "ana" - 原代码不符合规则1,应返回"palindrome" console.log(StringChallenge("mmop")); // 预期输出 "not possible" - 正常
修正方案
问题分析
原代码存在三个核心错误:
- 输入本身是回文时,返回原字符串而非规则要求的
"palindrome"; - 逻辑方向错误:返回的是保留的回文子串,而非题目要求的被移除的字符;
- 未限制移除字符数量(仅允许移除1或2个),而是遍历所有子串,违背题目规则。
修正后的代码
function StringChallenge(str) { // 工具函数:判断字符串是否为回文 const isPalindrome = (s) => s === s.split("").reverse().join(""); // 规则1:输入本身是回文的情况 if (isPalindrome(str)) { return "palindrome"; } const strLen = str.length; let removedChars = ""; let maxPalindromeLength = 0; // 优先尝试移除1个字符(因为得到的回文长度更长,符合最长要求) for (let i = 0; i < strLen; i++) { const modifiedStr = str.slice(0, i) + str.slice(i + 1); if (modifiedStr.length >= 3 && isPalindrome(modifiedStr)) { // 记录最长回文对应的移除字符,长度相同则保留更早移除的 if (modifiedStr.length > maxPalindromeLength) { maxPalindromeLength = modifiedStr.length; removedChars = str[i]; } else if (modifiedStr.length === maxPalindromeLength && !removedChars) { removedChars = str[i]; } } } // 移除1个字符已找到结果,直接返回 if (removedChars) { return removedChars; } // 尝试移除2个字符的情况 for (let i = 0; i < strLen; i++) { for (let j = i + 1; j < strLen; j++) { const modifiedStr = str.slice(0, i) + str.slice(i + 1, j) + str.slice(j + 1); if (modifiedStr.length >= 3 && isPalindrome(modifiedStr)) { const currentRemoved = str[i] + str[j]; // 同样优先选择最长回文,长度相同则保留更早的移除组合 if (modifiedStr.length > maxPalindromeLength) { maxPalindromeLength = modifiedStr.length; removedChars = currentRemoved; } else if (modifiedStr.length === maxPalindromeLength && !removedChars) { removedChars = currentRemoved; } } } } // 规则3:无法生成符合要求的回文 return removedChars ? removedChars : "not possible"; } // 测试验证 console.log(StringChallenge("kjjjhjjj")); // 输出 "k"(符合预期) console.log(StringChallenge("ana")); // 输出 "palindrome"(符合规则1) console.log(StringChallenge("mmop")); // 输出 "not possible"(符合规则3)
代码说明
- 封装
isPalindrome工具函数,简化回文判断逻辑; - 严格遵循规则优先级:先判断输入是否为回文,再尝试移除1个字符(优先保证最长回文),最后尝试移除2个字符;
- 全程记录被移除的字符而非保留的回文子串,完全匹配题目要求;
- 处理了长度相同的回文情况,优先保留更早出现的移除字符组合。
内容的提问来源于stack exchange,提问作者Ana Paula Teston
相关产品推荐
相关产品推荐

