题目链接:https://leetcode.com/problems/palindromic-substrings/#/description
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.
方法一 (dp)
int countSubstrings(string s) {
if(s.empty())
return 0;
if(s.size() == 1)
return 1;
int res = 0;
vector<vector<bool>> dp(s.size(), vector<bool>(s.size(), false));
for(int i = s.size() - 1; i>= 0; i--) {
dp[i][i] = true;
res++;
for(int j = i + 1; j < s.size(); j++) {
if(s[i] == s[j] && (i + 1 == j || dp[i + 1][j - 1])) {
dp[i][j] = true;
res++;
}
}
}
return res;
}
方法二:(dp)
class Solution {
public:
int countSubstrings(string s) {
int n = s.size(), count = 0;
vector<vector<int>> dp(n, vector<int> (n));
for ( int end = 0; end < n; ++end ) {
dp[end][end] = 1;
++count;
for ( int start = 0; start < end; ++start ) {
if ( s[start] == s[end] && (start+1 >= end-1 || dp[start+1][end-1])) {
dp[start][end] = 1;
++count;
}
}
}
return count;
}
};
方法三
class Solution {
public:
int countSubstrings(string s) {
int res = 0, n = s.length();
for(int i = 0; i<n ;i++ ){
// i or (i-1, i) is the middle index of the substring, 2*j + 1 or 2*j + 2 is the length of the substring
for(int j = 0; i-j >=0 && i+j <n && s[i-j] == s[i+j]; j++)res++;
for(int j = 0; i-1-j >=0 && i+j <n && s[i-1-j] == s[i+j];j++)res++;
}
return res;
}
};