LeetCode OJ ---- Longest Palindromic Substring

来源:互联网 发布:淘宝可以延长收货几天 编辑:程序博客网 时间:2024/05/17 01:07

题目描述

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
原创粉丝点击