Longest Palindromic Substring
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.
这道求最长回文子串的题目非常经典,也有非常多的解法。DP是其中非常经典的解法。具体解法有: 1:DP, 2:枚举中心,向两边走.
DP代码python代码会超时, C++代码如下:
class Solution { public: string longestPalindrome(string s) { const int n = s.size(); int maxlen = 1, start = 0; bool f[n][n]; fill_n(&f[0][0],n*n,false); for (int j=0;j<n;j++){ f[j][j] = true; for(int i=0;i<j;i++){ f[i][j] = (s[i]==s[j]&&(i+1>j-1||f[i+1][j-1])); if (f[i][j] and j-i+1 > maxlen){ maxlen = j-i+1; start = i; } } } return s.substr(start,maxlen); } };
枚举中心:
class Solution(object): def longestPalindrome(self, s): """ :type s: str :rtype: str """ if len(s)==0: return 0 maxLen=1 start=0 for i in xrange(len(s)): if i-maxLen >=1 and s[i-maxLen-1:i+1]==s[i-maxLen-1:i+1][::-1]: #剪枝 start=i-maxLen-1 maxLen+=2 continue if i-maxLen >=0 and s[i-maxLen:i+1]==s[i-maxLen:i+1][::-1]: start=i-maxLen maxLen+=1 return s[start:start+maxLen]
posted on 2016-05-05 14:31 Sheryl Wang 阅读(110) 评论(0) 编辑 收藏 举报