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

LeetCode – Refresh – Longest Palindromic Substring

时间:2015-03-20 08:05:24      阅读:123      评论:0      收藏:0      [点我收藏+]

标签:

O(n2):

 1 class Solution {
 2 public:
 3     string getP(string s, int start, int end) {
 4         while (start >= 0 && end < s.size() && s[start] == s[end]) {
 5             start--;
 6             end++;
 7         }
 8         return s.substr(start+1, end - start - 1);
 9     }
10     string longestPalindrome(string s) {
11         int len = s.size();
12         if (len < 2) return s;
13         string result = s.substr(0, 1);
14         for (int i = 0; i < len-1; i++) {
15             string s1 = getP(s, i, i);
16             if (s1.size() > result.size()) result = s1;
17             string s2 = getP(s, i, i+1);
18             if (s2.size() > result.size()) result = s2;
19         }
20         return result;
21     }
22 };

 

TBA (O(n))

LeetCode – Refresh – Longest Palindromic Substring

标签:

原文地址:http://www.cnblogs.com/shuashuashua/p/4352687.html

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