Dynamic Programming 部分总结
这部分主要总结动态规划。
动态规划最重要的两个点是找:
- dynamic state;
- state transition equation
语言: Python3
NO.5 Longest Palindromic Substring
1 | Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000. |
解题思路
假定动态规划矩阵为 DP(i,j),输入字符串为s
- State:DP(l, r) 每个substring s(l:r)是否为一个palindrome,如果是,赋予True值,如果不是,赋予False值
- State transition equation:DP(l,r) = True if s(l) == s(r) and DP(l+1, r-1) = True.
- Base case: DP(l,r) = True if l == r; DP(l,r) = True if s(l) == s(r) and l == r-1;
- 需要注意的一点是 : l <= r 这样在定义 DP矩阵的时候,只关注矩阵的一半右下角就可以了
Solution
1 | def longestPalindrome(self, s): |