LeetCode Palindrome Substrings (DP)

 

647. Palindromic Substrings
Medium

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.

 

Accepted
176.4K
Submissions
293.8K
class Solution {
    public int countSubstrings(String s) {
        
        
        boolean dp[][]  = new boolean [s.length()][s.length()];
        
        //  dp[i][j] = 
        
        //              if s.charAt(i) == s.charAt(j) then dp[i+1][j-1] +1;
        
        //              else dp[i+1][j-1];
        
        
        if(s==null||s.length()==0){
            return 0;
        }
        
       //every isolated character is a palindrome
        
        for(int i = 0; i< s.length(); i++){
            
            dp[i][i] =true;
        }
        
        int count=0;
        
        for(int d = 0;d<s.length();d++ ){
            
            for(int i = 0; i+d<s.length(); i++){
                int j = i+d;
                
              //System.out.println("i=== "+i+"  "+"j===  "+j+"!!!!"+s.charAt(i)+"---"+s.charAt(j));
                
                if(s.charAt(i)==s.charAt(j)){
                    
                   
                       dp[i][j]= (i+1 >= j-1) ? true : dp[i+1][j-1];
                    
                    /*
                    Or a much higher level way to think of this is:
If a substring with size less than or equal to 3, it will always be a palindrome if first and last characters are the same.
Once you are in inside the condition: if (s[i] == s[j]), you have 2 options:
- the substring size <= 3: we know it is true as explained above.
- the substring size is greater than 3: we use memoization
PS: j-i<=2 means the substring length is <= 3.
                    */
                }
                
                if(dp[i][j])
                    count++;
           
                
            }
        }
        
        return count;
        
         
    }
}

 

posted @ 2020-06-09 15:22  CodingYM  阅读(173)  评论(0编辑  收藏  举报