您的位置:首页 > 其它

LeetCode OJ ---- Longest Palindromic Substring

2016-03-04 18:19 363 查看

题目描述

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.

code(c++)

class Solution {
public:
string longestPalindrome(string s) {
size_t len = s.size();
int pre = 0;
int cur = 1;
int next = 2;
size_t max_length = 1;
size_t begin = pre;
if (len < 2)
return s;
if (len == 2)
return s[pre] == s[cur] ? s : s.substr(pre,1);
while((cur != len && next != len)){
size_t length = 0;
if(s[pre] != s[cur] && s[pre] != s[next]){
++pre;
++cur;
++next;
}
else{
int sameEleNum = 0;
if(s[pre] == s[cur]){
int count = cur + 1;
sameEleNum = 2;
while(count != len && s[pre] == s[count]){
++sameEleNum;
++count;
}
}
size_t breakPoint = pre;
if(sameEleNum != 0){
--pre;
cur += sameEleNum - 1;
length += sameEleNum;
while(pre >= 0 && cur != len &&
s[pre] == s[cur]){
length += 2;
--pre;
++cur;
}
if(length > max_length){
max_length = length;
begin = pre + 1;
}
}
else{
--pre;
++next;
length += 3;
while(pre >= 0 &&
next != len && s[pre] == s[next]){
length += 2;
--pre;
++next;
}
if(length > max_length){
max_length = length;
begin = pre + 1;
}
}

pre = breakPoint + 1;
cur = pre + 1;
next = cur + 1;
}
if(next == len && s[pre] == s[cur]){
if(max_length < 2){
max_length = 2;
begin = pre;
}
}
}
return s.substr(begin, max_length);
}
};


note:

要注意回文字符中间是否有连续相等的元素,有与没有会有不同的处理方法
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: