Skip to content

Commit 80e7c84

Browse files
authored
Create countPalindromicSubstrings.cpp
1 parent 3705bd4 commit 80e7c84

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
/**
2+
647. Palindromic Substrings
3+
Given a string s, return the number of palindromic substrings in it.
4+
5+
A string is a palindrome when it reads the same backward as forward.
6+
7+
A substring is a contiguous sequence of characters within the string.
8+
9+
10+
11+
Example 1:
12+
13+
Input: s = "abc"
14+
Output: 3
15+
Explanation: Three palindromic strings: "a", "b", "c".
16+
Example 2:
17+
18+
Input: s = "aaa"
19+
Output: 6
20+
Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa".
21+
22+
23+
Constraints:
24+
25+
1 <= s.length <= 1000
26+
s consists of lowercase English letters.
27+
**/
28+
29+
class Solution {
30+
public:
31+
int countSubstrings(string s) {
32+
int count = 0;
33+
int n = s.size();
34+
if(n == 1) return 1;
35+
bool dp[1001][1001] = {false};
36+
for(int i=0; i <n;++i ) {
37+
dp[i][i] = true;
38+
count++;
39+
}
40+
for(int i = n-1; i >=0; --i) {
41+
for(int j = i+1; j <n;++j) {
42+
if(s[i] == s[j]) {
43+
if(j-i==1 || dp[i+1][j-1] == true) {
44+
dp[i][j] = true;
45+
count++;
46+
}
47+
}
48+
}
49+
}
50+
return count;
51+
}
52+
};

0 commit comments

Comments
 (0)