647. Palindromic Substrings

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:

  1. The input string length won't exceed 1000.

题目含义:找出一个字符串中所有可能出现的回文子串的个数

方法一:像水的波纹一样,从两个位置(ij)开始依次往外扩散,直到不符合回文为止

 1     private int count;    
 2     
 3     //找到以i,j为中心,往外扩散能构成的回文串个数
 4     private void checkPalindrome(String s, int i, int j) {
 5         while(i>=0 && j<s.length() && s.charAt(i)==s.charAt(j)){    //Check for the palindrome string
 6             count++;    //Increment the count if palindromin substring found
 7             i--;    //To trace string in left direction
 8             j++;    //To trace string in right direction
 9         }
10     }    
11     
12     public int countSubstrings(String s) {
13         if (s.length()==0) return 0;
14         for (int i=0;i<s.length();i++)
15         {
16             checkPalindrome(s,i,i);
17             checkPalindrome(s,i,i+1);
18         }
19         return count;        
20     }

 方法二:dp[len][len]  代表[i,j]之间是否构成回文字符串

 1     public int countSubstrings(String s) {
 2         if(s == null || s.length() == 0)
 3             return 0;
 4         int len = s.length();
 5         int res = 0;
 6         boolean[][] dp = new boolean[len][len]; //代表[i,j]之间是否构成回文字符串
 7         for(int i = len - 1; i >= 0; i--){
 8             for(int j = i; j < len; j++){
 9                 //首先i和j位置上的字符要相等 ,其次i和j的距离不超过2,如果超过2了,则要求[i+1,j-1]能构成回文串
10                 if(s.charAt(i) == s.charAt(j) && (j - i <= 2 || dp[i + 1][j - 1])){
11                     dp[i][j] = true;
12                     res++;
13                 }
14             }
15         }
16         return res;     
17     }

 

posted @ 2017-10-18 15:47  daniel456  阅读(127)  评论(0编辑  收藏  举报