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.
Companies:
Pure Storage, Google, Facebook, Coursera, Amazon, Microsoft
Related Topics:
String, Dynamic Programming
Similar Questions:
- Longest Palindromic Substring (Medium)
- Longest Palindromic Subsequence (Medium)
- Palindromic Substrings (Medium)
// OJ: https://leetcode.com/problems/palindromic-substrings/
// Author: github.com/lzl124631x
// Time: O(N^2)
// Space: O(1)
class Solution {
public:
int countSubstrings(string s) {
int N = s.size(), ans = N;
for (int i = 1; i + 1 < N; ++i) {
for (int j = 1; i - j >= 0 && i + j < N && s[i - j] == s[i + j]; ++j, ++ans);
}
for (int i = 0; i + 1 < N; ++i) {
for (int j = 0; i - j >= 0 && i + 1 + j < N && s[i - j] == s[i + 1 + j]; ++j, ++ans);
}
return ans;
}
};