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

leetcode 5.Longest Palindromic Substring

时间:2015-01-06 23:07:00      阅读:208      评论:0      收藏:0      [点我收藏+]

标签:

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.

求最长回文子串,假设我们已知S[i...j]是回文子串,那么,若S[i-1] = S[j+1],则S[i-1,...,j+1]是回文子串。

用table[i][j]的true/false表示S[i,...,j]是否为回文子串,

可以得到递推公式:table[i][j] = table[i+1][j-1] && (S[i] == S[j]) (i+1 <= j-1, 即 i+2 <= j)

初始条件:

当j = i 时,table[i][j] = true;

当j = i + 1时,table[i][j] = (S[i] == S[j])

 1 string longestPalindrome(string s) 
 2     {
 3         bool table[1000][1000] = {false};
 4         int i, j, slen = s.length(), start = 0, maxlen = 1;
 5         
 6         for (i = 0; i < slen; i++)
 7             table[i][i] = true;
 8         for (i = 0; i < slen - 1; i++)
 9         {
10             j = i + 1;
11             if (s[i] == s[j])
12             {
13                 table[i][j] = true;
14                 start = i;
15                 maxlen = 2;
16             }
17         }
18         
19         for (int len = 3; len <= slen; len++)
20         {
21             for (i = 0; i < slen - len + 1; i++)
22             {
23                 j = i + len - 1;
24                 if (s[i] == s[j] && table[i + 1][j - 1])
25                 {
26                     table[i][j] = true;
27                     start = i;
28                     maxlen = len;
29                 }
30             }
31         }
32         
33         return s.substr(start, maxlen);
34     }

 

leetcode 5.Longest Palindromic Substring

标签:

原文地址:http://www.cnblogs.com/ym65536/p/4207123.html

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