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 @   CodingYM  阅读(176)  评论(0编辑  收藏  举报
编辑推荐:
· 大模型 Token 究竟是啥:图解大模型Token
· 35岁程序员的中年求职记:四次碰壁后的深度反思
· 继承的思维:从思维模式到架构设计的深度解析
· 如何在 .NET 中 使用 ANTLR4
· 后端思维之高并发处理方案
阅读排行:
· 感觉程序员要被 AI 淘汰了?学什么才有机会?
· BotSharp + MCP 三步实现智能体开发
· “你觉得客户需要”是杀死TA的最后一根稻草 | IPD集成产品开发
· dify升级,PostgreSQL数据库字段更新处理
· Java 与 LLM 大模型融合的技术革命:JBoltAI 如何重构企业级 AI 开发范式
点击右上角即可分享
微信分享提示