0647. Palindromic Substrings¶
Given a string, your task is to count how many palindromic substrings in this string.
The substrings with different start indexes or end indexes are counted as different substrings even they consist of same characters.
Example 1:
Input: "abc"
Output: 3
Explanation: Three palindromic strings: "a", "b", "c".
Example 2:
Input: "aaa"
Output: 6
Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa".
Note:
- The input string length won't exceed 1000.
Analysis¶
create a 2d dp, which stands for if dp[i][j] == true, then s[i:j] is a palindrome
- Outter loop: iterate all the length (0 - n) for the substring.
- Inner loop: iterate all the starting index of the substring. (ends at starting idx + length)
Edge case: when length <= 2, just set the to true and no need to check previous state
Time: O(n^2) Space: O(n^2)
Code¶
class Solution {
public:
int countSubstrings(string s) {
int n = s.size();
bool pal[n][n];
int res = 0;
memset(pal, 0, sizeof pal);
for (int d = 0; d < n; ++d) { // length
for (int i = 0; i + d < n; ++i) { // start pos
int j = i + d;
if (s[i] == s[j]) { // if length <= 2 AND s[i] == s[j], simply set pal[i][j] to true
pal[i][j] = (d <= 2) || pal[i + 1][j - 1];
}
if (pal[i][j]) res ++;
}
}
return res;
}
};
Last update:
April 1, 2022