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:
- 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; } }
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 大模型 Token 究竟是啥:图解大模型Token
· 35岁程序员的中年求职记:四次碰壁后的深度反思
· 继承的思维:从思维模式到架构设计的深度解析
· 如何在 .NET 中 使用 ANTLR4
· 后端思维之高并发处理方案
· 感觉程序员要被 AI 淘汰了?学什么才有机会?
· BotSharp + MCP 三步实现智能体开发
· “你觉得客户需要”是杀死TA的最后一根稻草 | IPD集成产品开发
· dify升级,PostgreSQL数据库字段更新处理
· Java 与 LLM 大模型融合的技术革命:JBoltAI 如何重构企业级 AI 开发范式