如何编写一个 Javascript 函数来按顺序从字符串中获取所有回文子序列?

子序列是从列表中选择的一组字符,同时保持它们的顺序。例如,字符串的子序列abc是[a, b, c, ab, ac, bc, abc].


现在,我需要编写一个函数来按顺序返回给定字符串中的所有回文子序列。例如,对于字符串acdapmpomp,输出应该是[a,c,d,p,m,o,aa,aca,ada,pmp,mm,mom,pp,ppp,pop,mpm,pmpmp]。


我的代码是:


function getAllPalindromicSubsequences(str) {

    var result = [];

    for (let i = 0; i < str.length; i++) {

        for (let j = i + 1; j < str.length + 1; j++) {

            if (str.slice(i, j).split("").reverse().join("") == str.slice(i, j)){

                result.push(str.slice(i, j));

            }

        }

    }

    return result;

}


console.log(getAllPalindromicSubsequences("acdapmpomp"));

但这会产生以下输出:


[

  'a', 'c', 'd',

  'a', 'p', 'pmp',

  'm', 'p', 'o',

  'm', 'p'

]

我犯了什么错误?正确的代码应该是什么?


长风秋雁
浏览 123回答 1
1回答

Qyouu

您可以采用递归方法收集所有字符并检查它们是否为回文。function getSub(string) {&nbsp; &nbsp; function isPalindrome(string) {&nbsp; &nbsp; &nbsp; &nbsp; let l = 0,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; r = string.length - 1;&nbsp; &nbsp; &nbsp; &nbsp; if (!string) return false;&nbsp; &nbsp; &nbsp; &nbsp; while (l < r) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (string[l] !== string[r]) return false;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; l++; r--;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return true;&nbsp; &nbsp; }&nbsp; &nbsp; function sub([character, ...rest], right = '') {&nbsp; &nbsp; &nbsp; &nbsp; if (isPalindrome(right) && !result.includes(right)) result.push(right);&nbsp; &nbsp; &nbsp; &nbsp; if (!character) return;&nbsp; &nbsp; &nbsp; &nbsp; sub(rest, right + character);&nbsp; &nbsp; &nbsp; &nbsp; sub(rest, right);&nbsp; &nbsp; }&nbsp; &nbsp; var result = [];&nbsp; &nbsp; sub([...string])&nbsp; &nbsp; return result;}console.log(getSub('acdapmpomp'));
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript