​welcome to my blog​

LeetCode Top 100 Liked Questions 647. Palindromic Substrings (Java版; Medium)

题目描述

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".
class Solution {
public int countSubstrings(String s) {
int n = s.length();
if(n==0){
return 0;
}
//dp[i][j]表示s[i,j]是否是回文子串
//dp[i][j] = dp[i+1][j-1] && s[i]==s[j]
boolean[][] dp = new boolean[n][n];
int res = 0;
for(int i=0; i<n; i++){
dp[i][i] = true;
res++;
}
for(int i=n-1; i>=0; i--){
for(int j=i+1; j<n; j++){
dp[i][j] = s.charAt(i)==s.charAt(j) && (j-i==1 || dp[i+1][j-1]);
if(dp[i][j]){
res++;
}
}
}
return res;

}
}

第一次做; 向两端扩张,核心:扩张函数接收两个参数

class Solution {
public int countSubstrings(String s) {
if(s==null || s.length()==0)
return 0;
int count=0;
for(int i=0; i<s.length(); i++){
//以自己为中心向两端扩张
count = count + expand(s,i,i);
//如果当前字符和下一个字符相同, 那么就可以以当前字符和下一个字符为中心向两端扩张
if(i+1<s.length() && s.charAt(i)==s.charAt(i+1))
count = count + expand(s,i,i+1);
}
return count;
}
public int expand(String s, int i, int j){
int count = 0;
while(i>=0 && j<s.length() && s.charAt(i) == s.charAt(j)){
count++;
i--;
j++;
}
return count;
}
}

​LeetCode优秀题解​​; 动态规划; dp[i][j]的含义:[i,j]范围上回文串的数量; dp[i+1][j-1]向外扩张一次后是dp[i][j]

Let me explain more.
If you are confused about dp[i + 1][j - 1], the best way to understand it is to refer to longest palindromic substring problem in lc.
dp[i + 1][j - 1] is referred to the string in between dp[i][j], which is the last status before expanding to dp[i][j], that's why we are using dp.
For j - i < 3, think that you have a string AXA, and j-i here is 2, since A is matched with A, X does not matter here.
So when the strings in between is less than or equal to 1 char, we can ignore it.
public int countSubstrings(String s) {
int n = s.length();
int res = 0;
boolean[][] dp = new boolean[n][n];
for (int i = n - 1; i >= 0; i--) {
for (int j = i; j < n; j++) {
dp[i][j] = s.charAt(i) == s.charAt(j) && (j - i < 3 || dp[i + 1][j - 1]);
if(dp[i][j]) ++res;
}
}
return res;
}