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.
1 class Solution { 2 public: 3 string longestPalindrome(string s) { 4 int n = s.size(); 5 if (n <= 1) return s; 6 7 int start = 0; 8 int maxlen = 0; 9 bool ispal[1000][1000] = {false}; 10 11 for (int i = 0; i < n; i++){ 12 for (int j = i; j >= 0; j--){ 13 if (s[i] == s[j] && (ispal[j+1][i-1] || j+1 > i-1)){ 14 ispal[j][i] = true; 15 if (i - j + 1 > maxlen){ 16 maxlen = i - j + 1; 17 start = j; 18 } 19 } 20 } 21 } 22 23 return s.substr(start, maxlen); 24 } 25 };
[LeetCode #5] Longest Palindromic Substring
原文:http://www.cnblogs.com/amadis/p/5925608.html