LeetCode:647. Palindromic Substrings

来源:互联网 发布:淘宝网品种销量排行榜 编辑:程序博客网 时间:2024/05/16 12:54

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.

题意:求字符串中回环子串的个数
分析:假设A[left,right]是回环的,如果A[left-1]==A[right+1],必然A[left-1,right+1]也是回环的。
因此必须找到一个遍历的顺序。只要找到回环子串的对称轴,然后向外扩展,就可以遍历解空间,需要注意回环串长度是奇数的(从长度为1的子串遍历),以及回环串长度是偶数的(从长度是2的子串遍历)。
代码如下:

class Solution {    public int countSubstrings(String s) {        if(s==null||s.length()==0)            return 0;        LinkedList<Integer> left=new LinkedList<Integer>();        LinkedList<Integer> right=new LinkedList<Integer>();        left.addFirst(0);        right.addFirst(0);        for(int i=1;i<s.length();i++){            left.addFirst(i);            right.addFirst(i);            if(s.charAt(i)==s.charAt(i-1))            {                left.addFirst(i-1);                right.addFirst(i);            }        }        int count=left.size();        while(left.size()>0){            int l=left.removeLast();            int r=right.removeLast();            while(l-1>=0&&r+1<s.length()&&s.charAt(l-1)==s.charAt(r+1)){                count++;                l--;                r++;            }        }        return count;    }}