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;
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; } }
|
References
647. Palindromic Substrings
剑指 Offer II 020. 回文子字符串的个数