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: 3Explanation: Three palindromic strings: "a", "b", "c".
Example 2:
Input: "aaa"Output: 6Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa".
Note:
- The input string length won't exceed 1000.
解释:这道题的关键是要遍历所有可能的结果。比如输入为:abc 需要遍历 (a,a)(a,b)(b,b)(b,c)(a,c)(c,c)(a,b,c),很明显只有三种是回文字符串。
方法一:中心遍历法
class Solution { private int cnt=0; public int countSubstrings(String s) { for(int i=0;i=0 && end
方法二:动态规划
公式:dp[i]=dp[i-1]+tmp;
dp[i]表示回文数总数。tmp是每趟的回文数。
class Solution { private boolean ifPalindromic(String s){ for(int i=0;i