leetcode第十题----- Longest Palindromic Substring

题目:

Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.

Example:

Input: "babad"

Output: "bab"

Note: "aba" is also a valid answer.

Example:

Input: "cbbd"

Output: "bb"


解题思路:题目要求的是最长回文子序列。而这种序列,从它的中心点的地方开始,往左和往右依次读的字符,每个都一样。依据这个特征,我们可以判断一个序列是不是回文子序列。我的解题思路就是,找到一个中心点,然后从它开始向左向右拓展,直到找到它完整的一串回文子序列。然后,接下来的事就简单了,将这个子序列的大小和当前记录的最大子序列的大小相比,并且记录些最大子序列的长度和内容。

代码如下:

class Solution {
public:
    string longestPalindrome(string input) {
       

int count = 0, max = 0;
string longest;
        
for (int i = 1; i < input.length(); i++) {
if (i+1 < input.length()) {
if (input[i-1] == input[i+1]) {
for (int j = 0 ; ;j++) {
if (i-1-j <0 || i+1+j >= input.length()) {
break;
}//防止数组越界 
if (input[i-1-j] == input[i+1+j]) {
count++;
} else {
break;
}
}
if (count >= max) {
max = count;
longest = "";
for (int k = 0; k < 2*count+1; k++) {
longest = longest+input[i-count+k];
}
}
                
count = 0;
                
}
}
        if (input[i-1] == input[i]) {
for (int j = 0 ; ;j++) {
if (i-1-j <0 || i+j >= input.length()) {
break;
}//防止数组越界 
if (input[i-1-j] == input[i+j]) {
count++;
} else {
break;
}
}
if (count > max) {
max = count;
longest = "";
for (int k = 0; k < 2*count; k++) {
longest = longest+input[i-count+k];
}
}
            
count = 0;
}

}
        
        if (max == 0) 
            longest = longest+input[0];
   return longest;
    }
};




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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值