leetcode講解--647. Palindromic Substrings

題目

Given a string, your task is to count how many palindromic substrings in this string.java

The substrings with different start indexes or end indexes are counted as different substrings even they consist of same characters.this

Example 1:code

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:leetcode

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

題目地址字符串

講解

題目的意思是:找出字符串中全部迴文串,不一樣位置的迴文串不算同一個。這道題我只能想到從左到右按照從1到s.length的長度依次掃N遍。並且這還不包括判斷是不是迴文串這一步所用的時間。而判斷迴文串顯然是能夠有重複計算的子問題的,因此要用到動態規劃。get

依舊是用規模從大到小的備忘錄遞歸解法。這道題作下來仍是挺輕鬆的,我發現我愈來愈喜歡用遞歸了,對遞歸的掌控力也變強了。input

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];
            }
        }
    }
}
相關文章
相關標籤/搜索