647. Palindromic Substrings 发表于 2022-01-11 Two Pointers12345678910111213141516171819202122class 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; }} DP12345678910111213141516171819202122232425262728293031class 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; }} Reference647. Palindromic Substrings剑指 Offer II 020. 回文子字符串的个数