647. 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.
// Dynamic programming
int countSubstrings(string s) { // time: O(n^2); space: O(n^2)
int n = s.size(), res = 0;
vector<vector<bool> > dp(n, vector<bool>(n, false)); // dp[i][j]: s[i...j] is a palindrome
for (int j = 0; j < n; ++j) {
for (int i = j; i >= 0; --i) {
if (s[i] == s[j]) {
if (j - i < 2 || dp[i + 1][j - 1]) {
dp[i][j] = true;
++res;
}
}
}
}
return res;
}
// Expand from the center
int countSubstrings(string s) { // time: (n^2); space: O(1)
int n = s.size(), res = 0;
for (int i = 0; i < n; ++i) {
helper(s, i, i, res); // odd length
helper(s, i, i + 1, res); // even length
}
return res;
}
void helper(string& s, int i, int j, int& res) {
while (i >= 0 && j < s.size() && s[i] == s[j]) {
++res;
--i, ++j;
}
}
Last updated
Was this helpful?