### 题目

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”.

Note: The input string length won’t exceed 1000.

### 朴素扩展法, $O(n^2)$

    core
<-  |  ->
longtimenosee

core
<-  |  ->
longtimenosee

core
<-  |  ->
longtimenosee

...
...


#### 代码

class Solution {
private char[] str = new char[0];
private int count;

public int countSubstrings(String s) {
init(s);
for (int i = 0; i < str.length; i++) {
extendPalindrome(i,i);      // odd
extendPalindrome(i,i+1);    // even
}
return count;
}
private void init(String s) {
str = s.toCharArray();
count = 0;
}
private void extendPalindrome(int lo, int hi) {
while (lo >= 0 && hi < str.length && (str[lo--] == str[hi++])) {
count++;
}
}
}


### 动态规划， $O(n^3)$

 new char
|
aaa[a]
aa[aa]
a[aaa]
[aaaa]


#### 代码

class Solution {
private static char[] str = new char[0];

public int countSubstrings(String s) {
init(s);
return dp(0);
}
private void init(String s) {
str = s.toCharArray();
}
private int dp(int start) {
if (start == str.length - 1) { return 1; }
int sub = dp(start+1);
for (int i = start; i < str.length; i++) {
if (isPalindrome(start,i)) {
sub++;
}
}
return sub;
}
private boolean isPalindrome(int lo, int hi) {
while (lo < hi) {
if (str[lo++] != str[hi--]) {
return false;
}
}
return true;
}
}