# 题目

5. 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.

# 思路

暴力破解(我和我同学也喜欢叫爆破):

固定下标,再固定长度,这样就能取出字符串。判断字符串是否是回文串且长度比原来的回文串长,若是,更新,若否,继续取字符串。

        // brute force: time O(n ^ 3) space O(n) result: TLE
        public string LongestPalindrome(string s)
        {
            char[] strs = s.ToCharArray();
            , end = ;

            ; i < strs.Length; i++) // start by index i
            {
                ; j > i; j--) // end by index j
                {
                    if (strs[i] == strs[j])
                    {
                        bool isPalindrome = true;
                        , l = j - ; k < l; k++, l--) // check whether substring is palindrome or not
                        {
                            if (strs[k] != strs[l])
                            {
                                isPalindrome = false;
                                break;
                            }
                        }

                        if (isPalindrome && j - i > end - start) // compare
                        {
                            start = i;
                            end = j;
                        }
                    }
                }
            }
            );
        }

暴力破解时间复杂度O(n ^ 3)空间复杂度O(n)时间TLE

我思维有点固化了。总想着先取字符串来判断是否是回文串,其实可以假定它是回文串,看它到底有多长。下面两个方法就是这样思考的。

优化暴力破解

对于每一个字符,分奇偶,分别尝试去找最长的回文串,并记录长度。

        // reference: https://discuss.leetcode.com/topic/23498/very-simple-clean-java-solution
        // optimize brute force: time O(n ^ 2) space O(n) result: 156ms
        public void palindrome(char[] strs, int left, int right, ref int start, ref int length) // judge palindrome
        {
             && right <= strs.Length -  && strs[left] != strs[right]) return;

             >=  && right +  <= strs.Length -  && strs[left - ] == strs[right + ])
            {
                left--;
                right++;
            }

            ;
            if (length < newLength)
            {
                start = left;
                length = newLength;
            }
        }

        // optimize brute force : time O(n ^ 2) space O(n) result:
        public string LongestPalindrome(string s)
        {
            ) return s;

            , length = ;
            char[] strs = s.ToCharArray();
            ; i < strs.Length; i++)
            {
                palindrome(strs, i, i, ref start, ref length); // recrusively judge
                palindrome(strs, i, i + , ref start, ref length);
            }
            return s.Substring(start, length);
        }

优化暴力破解时间复杂度O(n ^ 2)空间复杂度O(n)时间153ms

优化遍历
对于每一个字符,尝试去找最长的回文串,采取以下方法:
1、若是重复串,跳过重复部分(重复串怎么样都是回文串)。
2、非重复串,正常比对头尾。
3、设置下一个字符为非重复部分的下一个字符
比如baaaaab,遇到第一个a的时候,直接忽略5个a(也就是默认他是回文串了),从b开始尝试寻找回文串。同时下一个需要判断的字符是从第二个b开始。

# 解决(优化遍历)

        // reference: https://discuss.leetcode.com/topic/12187/simple-c-solution-8ms-13-lines/
        // like cheating method: time O(n ^ 2) space O(n) result: 132ms
        public string LongestPalindrome(string s)
        {
            char[] strs = s.ToCharArray();
            , maxLength = , start = ;

            )
            {
                int k = i, j = i; // j is left, i is middle, k is right
                 && strs[k] == strs[k + ]) k++; // skip duplicate char
                i = k + ; // set next begin index, we can skip duplicate char

                 && k < s.Length -  && strs[j - ] == strs[k + ]) // check palindrome
                {
                    j--;
                    k++;
                }

                ;
                if (newLength > maxLength) // compare
                {
                    start = j;
                    maxLength = newLength;
                }
            }

            return s.Substring(start, maxLength);
        }       

优化遍历时间复杂度O(n ^ 2)空间复杂度O(n)时间132ms

# 题外话

动态规划也可以做。

具体参考https://discuss.leetcode.com/topic/23498/very-simple-clean-java-solution/12。

状态转移方程:palindrome[i][j] = palindrome[i + 1][j - 1] && s[i] == s[j] 。palindrome[i][j]表示s[i]到s[j]是否是回文串。

题主太懒了,交给你们了。

# 测试用例

        static void Main(string[] args)
        {
            _5LongestPalindromicSubstring solution = new _5LongestPalindromicSubstring();
            Debug.Assert(solution.LongestPalindrome("dddddd") == "dddddd", "wrong 1");
            Debug.Assert(solution.LongestPalindrome("abbacdef") == "abba", "wrong 2");
            Debug.Assert(solution.LongestPalindrome("cabbadef") == "abba", "wrong 3");
            Debug.Assert(solution.LongestPalindrome("cabba") == "abba", "wrong 4");
            Debug.Assert(solution.LongestPalindrome("caacbbbbbad") == "bbbbb", "wrong 5");
            string veryLong = "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee";
            Debug.Assert(solution.LongestPalindrome(veryLong) == veryLong, "wrong 6");
            Debug.Assert(solution.LongestPalindrome("a") == "a", "wrong 7");
            Debug.Assert(solution.LongestPalindrome("abb") == "bb", "wrong 8");
        }

# 地址

Q: https://leetcode.com/problems/longest-palindromic-substring/

A: https://github.com/mofadeyunduo/LeetCode/blob/master/5LongestPalindromicSubstring/5LongestPalindromicSubstring.cs

(希望各位多多支持本人刚刚建立的GitHub和博客,谢谢,有问题可以邮件609092186@qq.com或者留言,我尽快回复)

LeetCode-5LongestPalindromicSubstring(C#)的更多相关文章

  1. 我为什么要写LeetCode的博客?

    # 增强学习成果 有一个研究成果,在学习中传授他人知识和讨论是最高效的做法,而看书则是最低效的做法(具体研究成果没找到地址).我写LeetCode博客主要目的是增强学习成果.当然,我也想出名,然而不知 ...

  2. LeetCode All in One 题目讲解汇总(持续更新中...)

    终于将LeetCode的免费题刷完了,真是漫长的第一遍啊,估计很多题都忘的差不多了,这次开个题目汇总贴,并附上每道题目的解题连接,方便之后查阅吧~ 477 Total Hamming Distance ...

  3. [LeetCode] Longest Substring with At Least K Repeating Characters 至少有K个重复字符的最长子字符串

    Find the length of the longest substring T of a given string (consists of lowercase letters only) su ...

  4. Leetcode 笔记 113 - Path Sum II

    题目链接:Path Sum II | LeetCode OJ Given a binary tree and a sum, find all root-to-leaf paths where each ...

  5. Leetcode 笔记 112 - Path Sum

    题目链接:Path Sum | LeetCode OJ Given a binary tree and a sum, determine if the tree has a root-to-leaf ...

  6. Leetcode 笔记 110 - Balanced Binary Tree

    题目链接:Balanced Binary Tree | LeetCode OJ Given a binary tree, determine if it is height-balanced. For ...

  7. Leetcode 笔记 100 - Same Tree

    题目链接:Same Tree | LeetCode OJ Given two binary trees, write a function to check if they are equal or ...

  8. Leetcode 笔记 99 - Recover Binary Search Tree

    题目链接:Recover Binary Search Tree | LeetCode OJ Two elements of a binary search tree (BST) are swapped ...

  9. Leetcode 笔记 98 - Validate Binary Search Tree

    题目链接:Validate Binary Search Tree | LeetCode OJ Given a binary tree, determine if it is a valid binar ...

  10. Leetcode 笔记 101 - Symmetric Tree

    题目链接:Symmetric Tree | LeetCode OJ Given a binary tree, check whether it is a mirror of itself (ie, s ...

随机推荐

  1. Pivot 和 Unpivot

    在TSQL中,使用Pivot和Unpivot运算符将一个关系表转换成另外一个关系表,两个命令实现的操作是“相反”的,但是,pivot之后,不能通过unpivot将数据还原.这两个运算符的操作数比较复杂 ...

  2. Cocos2d Android 环境搭建

    1.在开始之前,需要先准备好资源如下,如果安卓开发环境有了直接装第3.4. 1.JDK      点击下载 (1.6) 2.ADT(已经自带Android SDK)点击下载 3.NDK 点击下载 4. ...

  3. $ORACLE_HOME变量值末尾多“/”惹的祸

    之前一直误以为$ORACLE_HOME变量的路径中末尾多写一个"/"不会有影响. 今天做实验时碰到一个情景,发现并不是这样. 环境:OEL 5.7 + Oracle 10.2.0. ...

  4. 小兔JS教程(三)-- 彻底攻略JS回调函数

    这一讲来谈谈回调函数. 其实一句话就能概括这个东西: 回调函数就是把一个函数当做参数,传入另一个函数中.传进去的目的仅仅是为了在某个时刻去执行它. 如果不执行,那么你传一个函数进去干嘛呢? 就比如说对 ...

  5. 在centos7上安装ClamAV杀毒,并杀毒(centos随机英文10字母)成功

    前言 上传文件的时候发现总是失败,查看top发现有个进程一直cpu占用80%以上,而且名称还是随机数.kill之后,一会儿又重新生成了.突然发现居然没有在服务端杀毒的经历.在此处补齐. 安装clama ...

  6. iOS - 模态Model视图跳转和Push视图跳转的混合需求实现原理

    在研发中总会遇到一些莫名的需求,本着存在即合理的态度跟大家分享一下"模态Model视图跳转和Push视图跳转的需求实现",本文仅仅传授研发技术不传授产品以及UE的思想,请大家合理对 ...

  7. Atitit.研发团队的管理原则---立长不立贤与按资排辈原则

    Atitit.研发团队的管理原则---立长不立贤与按资排辈原则 1. 组织任命原则概述1 2. 历史的角度看,大部分组织使用的立长不立贤原则1 3. 论资排辈 立长不立贤原则1 3.1. 资格和辈分是 ...

  8. linux下使用shell 自动执行脚本文件

    以下实例本人在Centos6.5 64位操作系统中使用 一.定时复制文件 a.在/usr/local/wfjb_web_back目录下创建 tomcatBack.sh文件 文件内容: #将tomcat ...

  9. 性能测试工具 wrk 安装与使用

    介绍 今天给大家介绍一款开源的性能测试工具 wrk,简单易用,没有Load Runner那么复杂,他和 apache benchmark(ab)同属于性能测试工具,但是比 ab 功能更加强大,并且可以 ...

  10. RavenDB官网文档翻译系列第一

    本系列文章主要翻译自RavenDB官方文档,有些地方做了删减,有些内容整合在一起.欢迎有需要的朋友阅读.毕竟还是中文读起来更亲切吗.下面进入正题. 起航 获取RavenDB RavenDB可以通过Nu ...