超时了,129/132 var countSubstrings = function(s) { let num = 0 functionisHuiwen(t) { let p = 0;q = t.length-1 while (p<q){ if (t[p] != t[q]){ returnfalse } p++; q-- } returntrue } for (let i=0;i<s.length;i++){ for (let j=i+1;j<=s.length;j++){ console.log(isHuiwen(s.substring(i, j))) if (isHuiwen(s.substring(i,j))) num ++ } } return num };
动态规划 var countSubstrings = function(s) { let num = 0 let n = s.length let dp = Array.from({length:n},()=>Array(n).fill(false)) for(let i=n-1;i>=0;i--){ //j是尾巴,尾巴j大于等于头i for(let j=i;j<n;j++){ if (s[i]==s[j]){ if (j-i>1) { dp[i][j] = dp[i+1][j-1] } else dp[i][j] = true } if (dp[i][j] === true) num++ } } console.log(dp) return num };