码迷,mamicode.com
首页 > 其他好文 > 详细

Longest Palindromic Substring

时间:2014-09-09 12:14:08      阅读:200      评论:0      收藏:0      [点我收藏+]

标签: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 };

 

Longest Palindromic Substring

标签:style   blog   color   io   使用   for   div   sp   log   

原文地址:http://www.cnblogs.com/moderate-fish/p/3960782.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!