首页 > 其他 > 详细

Longest Palindromic Substring

时间:2014-04-23 10:49:17      阅读:377      评论: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.

Solution: 1. Time O(n^2), Space O(n^2)
2. Time O(n^2), Space O(n)
3. Time O(n^2), Space O(1) (actually much more efficient than 1 & 2)
4. Time O(n), Space O(n) (Manacher‘s Algorithm)

bubuko.com,布布扣
 1 class Solution {
 2 public:
 3     string longestPalindrome(string s) {
 4         int N = s.size();
 5         bool dp[N][N];
 6         pair<int, int> res = make_pair(0,0);
 7         for(int k = 0; k < N; k++) {
 8             for(int i = 0; i < N-k; i++) {
 9                 if(k == 0 || k == 1) {
10                     dp[i][i+k] = s[i] == s[i+k];
11                 }
12                 else {
13                     dp[i][i+k] = s[i] == s[i+k] ? dp[i+1][i+k-1] : false;
14                 }
15                 if(dp[i][i+k] && k +1 > res.second) {
16                     res = make_pair(i,k+1);
17                 }
18             }
19         }
20         return s.substr(res.first, res.second);
21         
22     }
23 };
bubuko.com,布布扣

 

Longest Palindromic Substring,布布扣,bubuko.com

Longest Palindromic Substring

原文:http://www.cnblogs.com/zhengjiankang/p/3682054.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!