<p>Given a string <code>s</code>, return <em>the number of <strong>palindromic substrings</strong> in it</em>.</p>

<p>A string is a <strong>palindrome</strong> when it reads the same backward as forward.</p>

<p>A <strong>substring</strong> is a contiguous sequence of characters within the string.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> s = &quot;abc&quot;
<strong>Output:</strong> 3
<strong>Explanation:</strong> Three palindromic strings: &quot;a&quot;, &quot;b&quot;, &quot;c&quot;.
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> s = &quot;aaa&quot;
<strong>Output:</strong> 6
<strong>Explanation:</strong> Six palindromic strings: &quot;a&quot;, &quot;a&quot;, &quot;a&quot;, &quot;aa&quot;, &quot;aa&quot;, &quot;aaa&quot;.
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= s.length &lt;= 1000</code></li>
	<li><code>s</code> consists of lowercase English letters.</li>
</ul>

class Solution {
public:
    int countSubstringsRecursive(int left, int right, string s,
                                 vector<vector<int>>& memo) {
        if (s[left] != s[right]) {
            memo[left][right] = 0;
            return 0;
        }

        if (memo[left][right] != -1) {
            return memo[left][right];
        }

        if (left == right) {
            int rightCount =
                right < s.size()
                    ? countSubstringsRecursive(left, right + 1, s, memo) + 1
                    : 1;
            int bothCount =
                left > 0 && right < s.size()
                    ? countSubstringsRecursive(left - 1, right + 1, s, memo) + 1
                    : 1;

            memo[left][right] = rightCount + bothCount;
            return rightCount + bothCount;
        } else {
            int bothCount =
                left > 0 && right < s.size()
                    ? countSubstringsRecursive(left - 1, right + 1, s, memo) + 1
                    : 1;

            memo[left][right] = bothCount;
            return bothCount;
        }
    }

    int countSubstrings(string s) {
        int count = 0;

        vector<vector<int>> memoize(s.length() + 1, vector<int>(s.length() + 1, -1));
        for (int i = 0; i < s.length(); i++) {
            count += countSubstringsRecursive(i, i, s, memoize);
        }

        return count - s.length();
    }
};
370164