# 题目

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. JavaScript之父Brendan Eich,Clojure 创建者Rich Hickey,Python创建者Van Rossum等编程大牛对程序员的职业建议

    软件开发是现时很火的职业.据美国劳动局发布的一项统计数据显示,从2014年至2024年,美国就业市场对开发人员的需求量将增长17%,而这个增长率比起所有职业的平均需求量高出了7%.很多人年轻人会选择编 ...

  2. 【.net 深呼吸】细说CodeDom(3):命名空间

    在上一篇文章中,老周介绍了表达式和语句,尽管老周没有把所有的内容都讲一遍,但相信大伙至少已经掌握基本用法.在本文中,咱们继续探讨 CodeDom 方面的奥秘,这一次咱们聊聊命名空间. 在开始之前,老周 ...

  3. JAVA回调机制(CallBack)详解

    序言 最近学习java,接触到了回调机制(CallBack).初识时感觉比较混乱,而且在网上搜索到的相关的讲解,要么一言带过,要么说的比较单纯的像是给CallBack做了一个定义.当然了,我在理解了回 ...

  4. Go web开发初探

    2017年的第一篇博客,也是第一次写博客,写的不好,请各位见谅. 本人之前一直学习java.java web,最近开始学习Go语言,所以也想了解一下Go语言中web的开发方式以及运行机制. 在< ...

  5. 深入浅出JavaScript之闭包(Closure)

    闭包(closure)是掌握Javascript从人门到深入一个非常重要的门槛,它是Javascript语言的一个难点,也是它的特色,很多高级应用都要依靠闭包实现.下面写下我的学习笔记~ 闭包-无处不 ...

  6. 一个IT人的成长路

    毕业四年多了,来深圳三年多了,经历了刚毕业的懵懂少年,成长为现在的成熟稳重青年.职场上,从刚毕业的小白,成长为现在可以成熟应对各种事情的老司机.经历过从初级研发工程师,到中级研发工程师,到高级研发工程 ...

  7. 模仿Linux内核kfifo实现的循环缓存

    想实现个循环缓冲区(Circular Buffer),搜了些资料多数是基于循环队列的实现方式.使用一个变量存放缓冲区中的数据长度或者空出来一个空间来判断缓冲区是否满了.偶然间看到分析Linux内核的循 ...

  8. css样式之background详解

    background用法详解: 1.background-color 属性设置元素的背景颜色 可能的值 color_name            规定颜色值为颜色名称的背景颜色(比如 red) he ...

  9. VS2015墙内创建ionic2 【利用nrm更换源,完美!】

    STEP 1 设置cnpm npm install -g cnpm --registry=https://registry.npm.taobao.org   一句话建立cnpm STEP 2 安装nr ...

  10. [转载]敏捷开发之Scrum扫盲篇

    现在敏捷开发是越来越火了,人人都在谈敏捷,人人都在学习Scrum和XP...      为了不落后他人,于是我也开始学习Scrum,今天主要是对我最近阅读的相关资料,根据自己的理解,用自己的话来讲述S ...