标签:style blog color io 使用 for div sp log
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 if( s.empty() ) { return string( "" ); } 5 int slen = s.length(), curlen = 1, ii = 0; 6 bool isPalindrome[2][1000]; 7 for( int step = 1; step < slen; ++step ) { 8 for( int i = 0; i <= slen-step; ++i ) { 9 int cur = (step-1) % 2; 10 if( step <= 2 ) { 11 isPalindrome[cur][i] = s[i] == s[i+step]; 12 } else { 13 isPalindrome[cur][i] = s[i] == s[i+step] && isPalindrome[cur][i+1]; 14 } 15 if( curlen < step+1 && isPalindrome[cur][i] ) { 16 ii = i; 17 curlen = step+1; 18 } 19 } 20 } 21 return s.substr( ii, curlen ); 22 } 23 };
标签:style blog color io 使用 for div sp log
原文地址:http://www.cnblogs.com/moderate-fish/p/3960782.html