# leetcode 第五题 找到最长回文串

73人阅读 评论(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.

（1）假定当前字符为回文串首字母，并将回文串正序列指针beginC指向当前字符，另回文串最后一个字符的指针endC指向最后一个字符

（2）判断endC和beginC

（3）若当前endC == beginC,则beginC++，endC--;

（4）若endC!=beginC,则beginC重新指向当前假定的回文串首字母，endC--;

class Solution {
public:
string longestPalindrome(string s) {
string temp;
if(s.length() <= 2)
return s;
int begin;
int end;
int max = 0;
for(int i = 0; i < s.length(); ++i)
{
begin = i;
end =  s.length() - 1;
int itbegin = i;
for(int j = s.length() - 1; j >= i; --j)
{
if(s[itbegin] != s[j])
{
end = j - 1;
itbegin = i;
}
else
{
itbegin++;
}
}
if(max <= end - begin)
{
string temp1;

max = end - begin;
for(int i = begin; i <= end; ++i)
{
string temp2;
temp2 = s[i];
temp1.append(temp2);
//cout << " " << s[i];
}
temp = temp1;
//cout << endl;
}
}

for(int i = s.length() - 1; i >= 0; --i)
{
end = i;
begin =  0;
int itbegin = i;
for(int j = 0; j <= i; ++j)
{
if(s[itbegin] != s[j])
{
begin = j + 1;
itbegin = i;
}
else
{
itbegin--;
}
}
if(max <= end - begin)
{
string temp1;

max = end - begin;
for(int i = begin; i <= end; ++i)
{
string temp2;
temp2 = s[i];
temp1.append(temp2);
//cout << " " << s[i];
}
temp = temp1;
//cout << endl;
}
}
return  temp;
}
};

class Solution {
public:
string longestPalindrome(string s) {
if(2 >= s.length())
return s;
bool found = false;
int maxLength = s.size();
string temp;
while(!found)
{
for(int i = 0; i <= s.size() - maxLength; ++i)
{
int begin = i;
int end = i+ maxLength -1;
for(; end >= begin; )
{
if(s[begin] != s[end])

break;
}
else

if (begin - end <= 0 && begin - end >= -1)
{
found = true;
temp = s.substr(i, i+maxLength);
break;
}
else
{
++begin;
--end;
}
}
}
if(found == true)
{
break;
}
}
--maxLength;
}
return temp;
}
}

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：6475次
• 积分：546
• 等级：
• 排名：千里之外
• 原创：48篇
• 转载：5篇
• 译文：0篇
• 评论：0条
评论排行