leetcode 第五题 找到最长回文串

第一篇博客,也是学习的开始!加油!

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;
}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值