LeetCode OJ ---- 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, 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:

  • 要注意回文字符中间是否有连续相等的元素,有与没有会有不同的处理方法
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值