【动态规划】子串、子序列问题
应用
应用1:Leetcode 647. 回文子串
题目
解题思路
动态规划
设
边界条件
当子串
状态转移
对于字符串
对于,任意一个子串
-
子串长度为
,即 ; -
子串长度大于
,若 ,且它的子串 是一个回文串。这里需要注意,当子串长度为
,即 时,它的子串 是一个空串""
。
否则,它就不是一个回文串。
因此,状态转移方程为:
这里,
表示逻辑与运算, 表示逻辑或运算。
代码
class Solution { public int countSubstrings(String s) { int n = s.length(); int result = 0; boolean [][] dp = new boolean[n][n]; for (int i = 0; i < n; i++) { dp[i][i] = true; result++; } for (int i = n - 1; i >= 0; i--) { for (int j = i + 1; j < n; j++ ) { if (s.charAt(i) == s.charAt(j)) { if (j - i <= 1) { dp[i][j] = true; } else { dp[i][j] = dp[i + 1][j - 1]; } } else { dp[i][j] = false; } if (dp[i][j]) { result++; } } } return result; } }
简化之后的代码如下:
class Solution { public int countSubstrings(String s) { int n = s.length(); int result = 0; boolean [][] dp = new boolean[n][n]; for (int i = 0; i < n; i++) { dp[i][i] = true; result++; } for (int i = n - 1; i >= 0; i--) { for (int j = i + 1; j < n; j++ ) { if (s.charAt(i) == s.charAt(j) && (j - i <= 1 || dp[i + 1][j - 1])) { dp[i][j] = true; result++; } } } return result; } }
本文作者:LARRY1024
本文链接:https://www.cnblogs.com/larry1024/p/17532149.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步