题目

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.

题目地址

讲解

题目的意思是:找出字符串中所有回文串,不同位置的回文串不算同一个。这道题我只能想到从左到右按照从1到s.length的长度依次扫N遍。而且这还不包括判断是否是回文串这一步所用的时间。而判断回文串显然是可以有重复计算的子问题的,所以要用到动态规划。

依旧是用规模从大到小的备忘录递归解法。这道题做下来还是挺轻松的,我发现我越来越喜欢用递归了,对递归的掌控力也变强了。

java代码

class Solution {
    private boolean[][] dp;
    public int countSubstrings(String s) {
        int result=0;
        dp = new boolean[s.length()][s.length()];
        for(int i=0;i<s.length();i++){
            for(int j=0;j+i<s.length();j++){
                dynamicProgramming(s, j, j+i);
            }
        }
        for(int i=0;i<dp.length;i++){
            for(int j=0;j<dp[i].length;j++){
                // System.out.println(i+","+j+"="+dp[i][j]);
                if(dp[i][j]){
                    result++;
                }
            }
        }
        return result;
    }
    
    private boolean dynamicProgramming(String s, int left, int right){
        if(left==right){
            dp[left][right] = true;
            return dp[left][right];
        }
        if(dp[left][right]){
            return dp[left][right];
        }
        if(s.charAt(left)!=s.charAt(right)){
            dp[left][right] = false;
            return dp[left][right];
        }else{
            if(right-left>1){
                dp[left][right] = dynamicProgramming(s, left+1, right-1);
                return dp[left][right];
            }else{
                dp[left][right] = true;
                return dp[left][right];
            }
        }
    }
}

liuqinh2s
42 声望13 粉丝

认真写代码,搞创作