LeetCode: Palindromic Substrings Solution

1/**
2 * @param {string} s
3 * @return {number}
4 */
5var countSubstrings = function (s) {
6 const N = s.length
7 const mem = Array.from({ length: N }, _ => Array(N).fill(null))
8
9 const isPalindrome = (i, j) => {
10 if (mem[i][j] !== null) {
11 return mem[i][j]
12 }
13
14 if (i >= j) {
15 return (mem[i][j] = 1)
16 }
17
18 if (s[i] !== s[j]) {
19 return (mem[i][j] = 0)
20 }
21
22 return (mem[i][j] = isPalindrome(i + 1, j - 1))
23 }
24
25 let res = 0
26
27 for (let i = 0; i < N; i++) {
28 for (let j = i; j < N; j++) {
29 res += isPalindrome(i, j) ? 1 : 0
30 }
31 }
32
33 return res
34}

Comments

Loading comments...

Tags

leetcode

string

dynamic programming

Apply and earn a $2,500 bonus once you're hired on your first job!

Clients from the Fortune 500 to Silicon Valley startups

Choose your own rate, get paid on time

From hourly, part-time, to full-time positions

Flexible remote working environment

A lot of open JavaScript jobs!!

Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.

Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.

Next Post

LeetCode: Evaluate The Bracket Pairs Of A String

HoningJS

Search Posts