647. 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.
Difficulty:Medium
Example:
Input: "aaa"
Output: 6
Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa".
方法1:暴力求解
- Time complexity : O ( n 2 ) O\left ( n^2 \right ) O(n2)
- Space complexity :
O
(
1
)
O\left ( 1 \right )
O(1)
思路:
数组长度为n,所有可能的中轴线有2n-1条,挨个遍历
判断过程:从中轴线向两侧扩散,左右相等便加一,不相等换下一个中轴线
class Solution {
public:
int countSubstrings(string s) {
int n = s.size(), res = 0;
for(int i = 0; i < 2*n-1; i++){
int left = i / 2;
int right = left + i % 2;
while(left >= 0 && right < n && s[left] == s[right]){
res++;
left--;
right++;
}
}
return res;
}
};
方法2:Dynamic Programming
- Time complexity : O ( n 2 ) O\left ( n^2 \right ) O(n2)
- Space complexity :
O
(
n
2
)
O\left ( n^2 \right )
O(n2)
?
思路:
dp[i][j]
表示区间[i,j]
是否是回文字符串,下面是子问题的解
dp[i][j] = s[i] == s[j] && (j - i <= 2 || dp[i + 1][j - 1])
class Solution {
public:
int countSubstrings(string s) {
int n = s.size(), res = 0;
vector < vector<bool>> dp(n, vector<bool>(n, false));
for (int i = n-1; i >= 0; i--) {
for (int j = i; j < n; j++) {
dp[i][j] = s[i] == s[j] && (j - i <= 2 || dp[i + 1][j - 1]);
if (dp[i][j]) res++;
}
}
return res;
}
};