68.Palindromic Substrings(回文字符串的个数)

Level:

  Medium

题目描述:

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

思路分析:

  将字符串中每个字符看成回文串中间的数,然后向两边扩展,由于串的长可能为奇数也可能为偶数,所以都得考虑

代码:

public class Solution{
    int res;
    public int countSubstrings(String s){
        if(s==null||s.length()==0)
            return 0;
        for(int i=0;i<s.length();i++){
            help(i,i,s);
            help(i,i+1,s);
        }
        return res;
    }
    public void help(int start,int end,String s){
        while(start>=0&&end<s.length()&&s.charAt(start)==s.charAt(end)){
            start--;
            end++;
            res++;
        }
    }
}

猜你喜欢

转载自www.cnblogs.com/yjxyy/p/11097872.html