Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000,
and there exists one unique longest palindromic substring.
Subscribe to see which companies asked this question
分析:
这是一个很经典的,证明算法魅力的实例。这里只打算掌握动态规划解法,那种线性时间的解法实在难想(像KMP算法一样先进行预处理)。
实际上在做的时候知道该怎么设定子问题,怎么初始化,但是却在怎么遍历迷糊了很久。
以下为别人的算法设计:
定义子问题:dp[i][j] 表示子串s[i…j]是否是回文,我们这样定义实际上变相知道了当前回文子串的长度,以及在原字符串中的位置。
1,初始化:
1),dp[i][i] = true (0 <= i <= n-1);
2),if(s[i]==s[i+1]), dp[i][i+1] = true (0 <= i <= n-2);
3),其余的初始化为false
2,在初始化基础上的递推过程
如果子问题dp[i+1][j-1] == true,并且扩张一个位置后s[i] == s[j]
显然当前位置,dp[i][j] = true,否则还是为false(意义就是,小的子串都不是回文,在此基础上更大的子串也不是回文)
在动态规划中更新最长回文的长度及起点以及长度即可
class Solution { public: string longestPalindrome(string s) { const int strLen = s.size(); int begin = 0; int maxLen = 1; bool table[1000][1000] = {false}; //前期的初始化1: 一个字符 for (int i = 0; i < strLen; i++) table[i][i] = true; //前期的初始化2:两个相等的相邻字符 for (int i = 0; i < strLen-1; i++) { if (s[i] == s[i+1]) { table[i][i+1] = true; begin = i; maxLen = 2; } } //递推3:寻找长度为3及其以上的回文子串 for (int len = 3; len <= strLen; len++) //当前子串的长度len { for (int i = 0; i < strLen-len+1; i++) //当前子串起始位置i { int j = i+len-1; //子串末尾位置j --》j-i=len-1 if (s[i] == s[j] && table[i+1][j-1]) { table[i][j] = true; begin = i; maxLen = len; } } } return s.substr(begin, maxLen); } };
注:本博文为EbowTang原创,后续可能继续更新本文。如果转载,请务必复制本条信息!
原文地址:http://blog.csdn.net/ebowtang/article/details/50698672
原作者博客:http://blog.csdn.net/ebowtang
<LeetCode OJ> 5. Longest Palindromic Substring
原文:http://blog.csdn.net/ebowtang/article/details/50698672