Poison

647. Palindromic Substrings

Two Pointers
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public int countSubstrings(String s) {
int count = 0;
for (int i = 0; i < s.length(); i++) {
count += tryExpand(s, i, i);
count += tryExpand(s, i, i + 1);
}

return count;
}

private int tryExpand(String s, int i, int j) {
int count = 0;
while (i >= 0 && j < s.length() && s.charAt(i) == s.charAt(j)) {
i--;
j++;
count++;
}

return count;
}
}
DP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Solution {
public int countSubstrings(String s) {
int n = s.length();
int count = 0;

// 定义 dp[i][j] 为字符串 s[i][j] 是否为回文字符串
boolean[][] dp = new boolean[n][n];

for (int i = n - 1; i >= 0; i--) {
dp[i][i] = true;
count++;

for (int j = i + 1; j < n; j++) {
if (s.charAt(i) == s.charAt(j)) {
// 注意不要忘记处理两个字符的特殊情况
if (j - i + 1 == 2) {
dp[i][j] = true;
} else {
dp[i][j] = dp[i + 1][j - 1];
}
}

if (dp[i][j]) {
count++;
}
}
}

return count;
}
}
Reference

647. Palindromic Substrings
剑指 Offer II 020. 回文子字符串的个数