1. 程式人生 > >LeetCode 647 : Palindromic Substrings(java)

LeetCode 647 : Palindromic Substrings(java)

原題

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:
The input string length won’t exceed 1000.

思路

求字串的迴文子串個數。假定子串內容相同但index不同認定為不同得子串。比如:在”aaa”中,共有 “a”, “a”, “a”, “aa”, “aa”, “aaa”六個迴文子串,前三個迴文 “a”, “a”, “a”就是內容相同但是index分別為0,1,2,所以為不同的子串。
很明顯這是一道dp的題,從左到右遍歷字串,每次加進一個字元,遞推公式為dp[i]=dp[i-1]+tmpNum。其中,tmpNum為新加進一個字元後新增加的迴文子串的個數。當遍歷到index=i時,只要看看在i之前的index j,能否構成substring(j,i+1)的迴文子串。最後結果是dp[len-1]+len,其中len為字串的長度,因為字串每個字元都為迴文子串。

程式碼

public class Solution {
    public boolean isPalindromic(String s){
        for(int i=0;i<(s.length()/2);i++)
            if(s.charAt(i)!=s.charAt(s.length()-1-i))
                return false;
        return true;
    }
    public int countSubstrings(String s) {
        int len=s.length();
        int
[] dp=new int[len]; for(int i=1;i<len;i++){ int tmpNum=0; for(int j=0;j<i;j++) if(s.charAt(i)==s.charAt(j)){ String subStr=s.substring(j,i+1); if(isPalindromic(subStr)) tmpNum++; } dp[i]=dp[i-1]+tmpNum; } return dp[len-1]+len; } }