第一篇博客,也是学习的开始!加油!
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;
}
};
后面看到另一种方法,比较好理解,也是暴力破解。http://www.xuebuyuan.com/1387904.html
大致的思路是从回文串长度做文章,先假定回文串长度为字符串长度需找是否存在,若不存在,就将回文串长度减一,直到找到为止。在VS2010上测试可以运行,但是在leetcode会显示超时
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;
}
}