Leetcode 5. Longest Palindromic Substring(字符串)

来源:互联网 发布:干洗衣店软件 编辑:程序博客网 时间:2024/05/20 17:41

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.

Difficulty: Medium

分析:寻找字符串中的最长回文序列,考虑回文序列的特性,我们从字符串的中间往两边搜索比较好,但是还是需要考虑序列长度是单数和双数的区别。

class Solution {public:    string longestPalindrome(string s)     {        int start,curLen,maxStart=0,maxLen=1;        int len=s.length();        if(len<2)            return s;        for(int i=0;i<len-1;i++)        {            curLen=1;            start=i;            //单数情况            for(int j=1;i-j>=0,i+j<len;j++)            {                if(s[i-j]!=s[i+j])                    break;                curLen+=2;                start-=1;            }            if(curLen>maxLen)            {                maxLen=curLen;                maxStart=start;            }            //双数情况            if(s[i]==s[i+1])            {                curLen=2;                start=i;                for(int j=1;i-j>=0,i+j+1<len;j++)                {                    if(s[i-j]!=s[i+j+1])                        break;                    curLen+=2;                    start-=1;                }                if(curLen>maxLen)                {                    maxLen=curLen;                    maxStart=start;                }            }        }        s.assign(s,maxStart,maxLen);        return s;    }};

这个算法运行时间为60ms,主要思路还是正确的,后来看到别人有的方法可以将单双数两种情况结合起来,速度更快,主要是先搜索连续相同的字符,因为双数情况下最中间两个字符肯定相同,这样就至少有两个字符是一样的了。

0 0