DEV Community

codingpineapple
codingpineapple

Posted on

2 2

LeetCode 647. Palindromic Substrings (javascript solution)

Description:

Given a string, your task is to count how many palindromic substrings in this string.

The substrings with different start indexes or end indexes are counted as different substrings even they consist of same characters.

Solution:

Time Complexity : O(n^2)
Space Complexity: O(n^2)

var countSubstrings = function(s) {
    const n = s.length;
    const dp = [...Array(n)].map(() => Array(n).fill(false));
    let count = 0;
    // Base case: single letter substrings
    for(let i = 0; i < n; i++) {
        dp[i][i] = true;
        count++
    }

    // Base case: double letter substrings
    for(let i = 0; i < n-1; i++) {
        dp[i][i+1] = (s[i] === s[i+1]);
        dp[i][i+1] && count++;
    }

    // substrings longer than 2 chars
    for(let len = 3; len <= n; len++) {
        let start = 0, end = start+len-1;

        while(end < n) {
            dp[start][end] = (dp[start+1][end-1] && s[start] === s[end]);
            dp[start][end] && count++;
            start++; end++;
        }
    }
    return count;
};
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay