标签:
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, and the state transfer:
f(i, j) = ture; if i == j
S[i] == S[j] ,if j = i + 1
S[i] == S[j] and f(i + 1, j - 1) ,if j > i + 1
class Solution { public: string longestPalindrome(string s) { size_t len = s.size(); char f[len][len]; size_t start = 0; size_t max = 0; memset(f,0,sizeof(f)); for(int i = 0; i < len; i++) { for(int j = 0; j <= i; j++) { if((j == i) || (i == (j+1) && s[i] == s[j]) || ((i > (j + 1)) && s[i] == s[j] && f[j+1][i-1])) { f[j][i] = 1; //cout << "f["<<j<<"][" <<i<<"]\n"; if((i - j +1) > max) { start = j; max = i - j + 1; // cout << "start\t" <<start <<endl; // cout << "max\t" <<max<<endl; } } } } return s.substr(start, max); } };
方法二:LCS+ reverse str
[LeetCode] Longest Palindromic Substring
标签:
原文地址:http://www.cnblogs.com/diegodu/p/4247833.html