var s = "aaabbb"; var str = s.split(""); var print = (str) => { let n = str.length; let dp = new Array(n).fill(0).map(() => new Array(n).fill(0)); for (let i = n - 1; i >= 0; i--) { dp[i][i] = 1; for (let j = i + 1; j < n; j++) { if (str[i] === str[j]) { dp[i][j] = dp[i][j - 1]; } else { let min = Number.MAX_SAFE_INTEGER; for (let k = i; k < j; k++) { min = Math.min(min, dp[i][k] + dp[k + 1][j]); } dp[i][j] = min; } } } return dp[0][n - 1]; } console.log(print(str))