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.

题意:

给出一个字符串,求它的回文子串的个数,起始位置或结束位置不同也算不同的回文子串。

思路:

囿于之前的老思路,dp[][j]=s[i]==s[j]?dp[i+1][j]+dp[i][j-1]:dp[i+1][j]+dp[i][j-1]-dp[i+1][j-1]。实质上给dp[i][j]一个bool值,是回文子串就是1,最后找出1的个数即可,因为二重循环遍历过程不存在重复遍历。

代码:

class Solution {
    public int countSubstrings(String s) {
        int l=s.length();
        int [][]dp=new int [l+1][l+1];
        for(int i=1;i<=l;i++)
        {
            for(int j=i;j<=l;j++)
                dp[i][j]=0;
        }
        int res=0;
        for(int i=1;i<=l;i++)
        {
            for(int j=1;j<=i;j++)
            {
                if(s.charAt(i-1)==s.charAt(j-1)&&(i-j<=2||dp[i-1][j+1]==1))
                    dp[i][j]=1;
                if(dp[i][j]==1)
                    res++;
            }
        }
        return res;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_36718317/article/details/79891531