一天一道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.中心扩展法

看到这个题首先想到的就是中心扩展法,遍历每一个字符,然后以该字符为中心向四周扩展,这种方法的时间复杂度为O(N^2),但是需要注意的是,奇数和偶数回文字符串需要区别对待,如aba和abba都是回文字符串。

class Solution {
public:
    string longestPalindrome(string s) {
        int max1=0;//奇数最长子串
        int max2=0;//偶数最长子串
        int idx1=0;//奇数最长子串的中心字符
        int idx2=0;//偶数最长子串的中心字符
        string result;
        for(int i = 0 ; i < s.length() ; ++i)
        {
            int j = i;
            int z = i;
            int count1=0;
            int count2=0;
            //计算奇数最长回文字符串
            while((++z<s.length()) && (--j>=0) && (s[z] == s[j]))
            {
                count1+=2;
                if(count1 > max1)
                {
                    max1=count1;
                    idx1 = i;
                }
            }
            //计算偶数最长回文字符串
            j = i;
            z = i+1;
            while((z<s.length()) && (j>=0) &&(s[z] == s[j]))
            {
                count2+=2;
                if(count2 > max2)
                {
                    max2=count2;
                    idx2 = i;
                }
                z++;
                j--;
            }
        }
        if(max1+1>max2) result = s.substr(idx1-max1/2,max1+1);
        else result = s.substr(idx2-max2/2+1,max2);
        return result;
    }
};

2.中心扩展法的优化

区分奇数和偶数显得程序比较臃肿,我们可以利用“改造“字符串来避免这种情况。如aba改成#a#b#a#,abba改成#a#b#b#a,这样就不用区分奇偶了。

class Solution {
public:
    string longestPalindrome(string s) {
        int max=0;
        int idx=0;
        string temp[2005];
        //改造字符串
        int j = 0;
        for(int i = 0; i < s.length() ; ++i)
        {
            temp[j++] = '#';
            temp[j++] = s[i];
        }
        temp[j++] = '#';
        temp[j] = '\0';
        for(int i = 0 ; i <2*s.length()+1 ; ++i)
        {
            int j = i;
            int z = i;
            int count=0;
            //计算奇数最长回文字符串
            while((++z<(2*s.length()+1)) && (--j>=0) && (temp[z] == temp[j]))
            {
                count++;
                if(count > max)
                {
                    max=count;
                    idx = i;
                }
            } 

        }
        return s.substr((idx-max)/2,max);
    }
};

3.动态规划法

DP算法的思想就是记录每一个回文子串的位置,在每一次判断是否为回文子串的时候先判断它的子串是不是回文,例如,用map[i][j]记录i到j为回文数组,如果这个时候s[i-1]==s[j+1],那么就能在O(1)时间内判断[i-1,j+1]是否为回文了。

动态规划法的时间复杂度为O(n^2).

class Solution {
public:
    string longestPalindrome(string s) {
        int len = s.length();
        int idx = 0;//记录最长回文字符的开始处
        int max = 1;//记录最长回文字符的长度
        int map[1000][1000] = {0};//记录i到j是否为回文子串
        for(int i = 0 ; i < len ; ++i)
        {
            map[i][i] = 1;//初始化长度为1的回文子串
        }
        for(int i = 0 ; i < len ; ++i)
        {
            if(s[i] == s[i+1])//初始化长度为2的子串
            {
                map[i][i+1] = 1;
                idx = i;
                max = 2;
            }
        }

        for(int plen = 3 ; plen <= len ; plen++)//从长度为3开始算起
        {//plen代表当前判断的回文子串的长度
            for(int j = 0 ; j < len - plen +1 ; j++)
            {
                int z = plen+j-1;//z为回文子串的尾序号
                if (s[j] == s[z] && map[j+1][z-1]) {
                //O(1)时间内判断j到z是否回文
                    map[j][z] = 1;
                    idx = j;
                    max = plen;
                }
            }
        }
        return s.substr(idx,max);//返回子串
    }
};

4.经典的Manacher算法,O(n)复杂度

算法步骤:

step1:跟解法2一样,改造字符串:

abba –> $#a#b#b#a#

注:加’$’是为了避免处理越界问题

step2:用p[i]记录以i为中心点的回文字符串长度

改造后的字符串:$#a#b#b#a#

p[]数组的值:121242121

注:p[i]-1 = 源字符串中回文子串长度

step3:利用DP的思想来求解p[]

利用中心扩展法求以i为中心的最长回文串

while(i+p[i] < temps.length() && temps[i-p[i]] == temps[i+p[i]]) p[i]++;

利用p[],mx,id记录的已有回文字符串的长度来避免大量重复的匹配

if(mx > i) p[i] = p[2*id-i] < (mx-i) ? p[2*id-i]:(mx-i);

注:p[2*id-i]为i关于j对称的点的回文串长度

mx为i之前的回文串延伸到右边的最长位置,id为该回文串的中间值

class Solution {
public:
    string longestPalindrome(string s) {
        string temps;
        temps+="$#";//加$是为了避免处理越界情况,减小时间复杂度
        for(int i = 0 ; i < s.length() ; ++i)//
        {
            temps+=s[i];
            temps+="#";
        }
        int *p = new int[temps.length()];//p[i]记录以i为中心的回文串长度
        memset(p, 0, sizeof(p));

        int max = 0,idx = 0;//max记录最长回文串的长度,idx记录最长回文串的中心位置
        int mx = 0,id = 0;//mx记录i之前的最长回文串延伸到最右边的位置,id记录该字符串的中心位置
        for(int i = 1; i < temps.length() ; ++i)
        {
            if(mx > i)
            {
                p[i] = p[2*id-i] < (mx-i) ? p[2*id-i]:(mx-i);
            }
            else
                p[i] = 1;

            while(i+p[i] < temps.length() && temps[i-p[i]] == temps[i+p[i]])
            {
                p[i]++;
            }
            if(i+p[i]>mx)
            {
                id = i;
                mx = i+p[i];
                if(p[i]>max)
                {
                    max = p[i];
                    idx = id;
                }
            }
        }
        max--;
        return s.substr((idx-max)/2,max);
    }
};

该算法的时间复杂度为O(n)。

以上代码在LeetCode中均Accepted。

【一天一道LeetCode】#5 Longest Palindromic Substring的更多相关文章

  1. LeetCode(4) || Longest Palindromic Substring 与 Manacher 线性算法

    LeetCode(4) || Longest Palindromic Substring 与 Manacher 线性算法 题记 本文是LeetCode题库的第五题,没想到做这些题的速度会这么慢,工作之 ...

  2. Leetcode 5. Longest Palindromic Substring(最长回文子串, Manacher算法)

    Leetcode 5. Longest Palindromic Substring(最长回文子串, Manacher算法) Given a string s, find the longest pal ...

  3. 求最长回文子串 - leetcode 5. Longest Palindromic Substring

    写在前面:忍不住吐槽几句今天上海的天气,次奥,鞋子里都能养鱼了...裤子也全湿了,衣服也全湿了,关键是这天气还打空调,只能瑟瑟发抖祈祷不要感冒了.... 前后切了一百零几道leetcode的题(sol ...

  4. LeetCode 5 Longest Palindromic Substring(最长子序列)

    题目来源:https://leetcode.com/problems/longest-palindromic-substring/ Given a string S, find the longest ...

  5. 【JAVA、C++】LeetCode 005 Longest Palindromic Substring

    Given a string S, find the longest palindromic substring in S. You may assume that the maximum lengt ...

  6. leetcode:Longest Palindromic Substring(求最大的回文字符串)

    Question:Given a string S, find the longest palindromic substring in S. You may assume that the maxi ...

  7. [LeetCode][Python]Longest Palindromic Substring

    # -*- coding: utf8 -*-'''__author__ = 'dabay.wang@gmail.com'https://oj.leetcode.com/problems/longest ...

  8. 【LeetCode】Longest Palindromic Substring 解题报告

    DP.KMP什么的都太高大上了.自己想了个朴素的遍历方法. [题目] Given a string S, find the longest palindromic substring in S. Yo ...

  9. [LeetCode] 5. Longest Palindromic Substring 最长回文子串

    Given a string s, find the longest palindromic substring in s. You may assume that the maximum lengt ...

  10. 最长回文子串-LeetCode 5 Longest Palindromic Substring

    题目描述 Given a string S, find the longest palindromic substring in S. You may assume that the maximum ...

随机推荐

  1. Android简易实战教程--第三十九话《Chronometer实现倒计时》

    Android提供了实现按照秒计时的API,今天就是用这个API实现简单的倒计时. 来个布局: <?xml version="1.0" encoding="utf- ...

  2. 【SSH系列】Hibernate映射 -- 一对一单向关联映射

     映射原理       一对一关联映射:两个实体对象之间是一对一的关联映射,即一个对象只能与另外唯一的一个对象相对应.有两种策略可以实现一对一的关联映射:       a.主键关联:即让两个对象具有相 ...

  3. Basic Git commands

    Basic Git commands Skip to end of metadata Created by Paul Watson [Atlassian], last modified on Nov ...

  4. Android简易实战教程--第三十话《撕衣美女》

    此篇邪恶一些,给单身屌丝发点"福利",通过图片的绘制,给美女脱掉衣服. 原理:图片覆盖图片,通过画笔对顶端的图片做一些特效处理,即手指触摸的地方,设置为透明.即可显示最底部的美女图 ...

  5. Android的SharedPreferences(首选项)保存键值对

    使用共享首选项 如果您有想要保存的相对较小键值集合,您应使用 SharedPreferences API.SharedPreferences 对象指向包含键值对的文件并提供读写这些文件的简单方法. 每 ...

  6. android studio的快捷键设置的和eclispe一样

    最近安装了android studio,但是习惯了使用eclispe的快捷键,所以我也把android studio的快捷键设置的和eclipse一样. 具体如下: 1.快捷键 Android Stu ...

  7. memcached实战系列(二)memcached参数以及启动

    memcached启动的时候配置的参数也比较多.在这里我就做一个汇总,需要的时候直接查看参数以及参数的含义. 下面是参数的定义以及解释. 1.1.1. 参数说明 -d选项是启动一个守护进程 -m是分配 ...

  8. Dynamics CRM 2013 Homepage Ribbon 按钮引用多个Javascript资源

    在CRM的开发中ribbon的开发是比较重要的一环,很多客制化的功能都需要动用ribbon区,CRM2013中的名字已经改叫command bar了,但从老版本过来的人都还是习惯叫他ribbon. R ...

  9. 初探linux子系统集之timer子系统(三)

    因为现在的linux虽然还是可以使用低精度的timer,但是趋势是高精度hrtimer,所以上一篇试着翻译一下hrtimer的一些介绍,翻译的不是很好,看来英语还得好好学习啊,下面还是好好学习下lin ...

  10. android notification,notificationmanager详解

    我们知道在使用Android的通知的时候一定会用到NotificationManager . Notification这两个类,这两个类的作用分别是: NotificationManager :  是 ...