Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit defcccf

Browse filesBrowse files
authored
Create 27 palindromicSubstrings.cpp
1 parent fe1227b commit defcccf
Copy full SHA for defcccf

File tree

Expand file treeCollapse file tree

1 file changed

+31
-0
lines changed
Filter options
Expand file treeCollapse file tree

1 file changed

+31
-0
lines changed
+31Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
class Solution {
2+
public:
3+
int countSubstrings(string s) {
4+
int n = s.size(), ans = 0;
5+
6+
if (n <= 0)
7+
return 0;
8+
9+
bool dp[n][n];
10+
fill_n(*dp, n * n, false);
11+
12+
// Base case: single letter substrings
13+
for (int i = 0; i < n; ++i, ++ans)
14+
dp[i][i] = true;
15+
16+
// Base case: double letter substrings
17+
for (int i = 0; i < n - 1; ++i) {
18+
dp[i][i + 1] = (s[i] == s[i + 1]);
19+
ans += dp[i][i + 1];
20+
}
21+
22+
// All other cases: substrings of length 3 to n
23+
for (int len = 3; len <= n; ++len)
24+
for (int i = 0, j = i + len - 1; j < n; ++i, ++j) {
25+
dp[i][j] = dp[i + 1][j - 1] && (s[i] == s[j]);
26+
ans += dp[i][j];
27+
}
28+
29+
return ans;
30+
}
31+
};

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.