1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36 | class Solution {
private:
static constexpr int SIZE = 1005;
bool vis[SIZE][SIZE] = {0};
bool cache[SIZE][SIZE] = {0};
int N;
string str;
bool dp(int i, int j) {
if (vis[i][j])
return cache[i][j];
vis[i][j] = true;
if (i >= j) {
cache[i][j] = true;
return cache[i][j];
}
if (this->str[i] == this->str[j]) {
cache[i][j] = dp(i + 1, j - 1);
return cache[i][j];
}
cache[i][j] = false;
return cache[i][j];
}
public:
int countSubstrings(string s) {
this->N = s.size();
this->str = s;
int ans = 0;
for (int i = 0; i < N; i++)
for (int j = i; j < N; j++)
if (dp(i, j))
ans++;
return ans;
}
};
|