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



回文子串的个数


java:
 1 class Solution {
 2     private int cnt = 0 ;
 3     
 4     public int countSubstrings(String s) {
 5         for(int i = 0 ; i < s.length() ; i++){
 6             extendSubstrings(s,i,i) ;
 7             extendSubstrings(s,i,i+1) ;
 8         }
 9         return cnt ;
10     }
11     
12     private void extendSubstrings(String s , int left , int right){
13         while(left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)){
14             left-- ;
15             right++ ;
16             cnt++ ;
17         }
18     }
19 }

 

posted @ 2019-01-11 10:52  __Meng  阅读(151)  评论(0编辑  收藏  举报