Palindromic Substrings

来源:互联网 发布:三国志9最新优化伴侣 编辑:程序博客网 时间:2024/06/04 23:57


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:

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

跟那道longest palindrome 类似, 不过方向正好反过来。记录最长回文的时候,双指针从外往里扫; 而这道题应该从里边往外边扫, 碰到一个回文串,就+1,然后再往外扩展判断。另外回文分为两种,一种是偶数个,一种是技术个,都统计就可以了。

代码:

class Solution {        private int count = 0;    public int countSubstrings(String s) {        if(s == null || s.length() == 0) return 0;        for(int i=0;i<s.length();i++) {            countPalindrome(s, i, i); // odd            countPalindrome(s, i, i+1);// even        }        return count;    }    private void countPalindrome(String s, int i, int j) {        while(i>=0 && j <s.length() && s.charAt(i) == s.charAt(j)) {            i--; j++; count++;        }    }}