# 题目

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. 小兔JS教程(四)-- 彻底攻略JS数组

    在开始本章之前,先给出上一节的答案,参考答案地址: http://www.xiaotublog.com/demo.html?path=homework/03/index2 1.JS数组的三大特性 在J ...

  2. Xcode 锁终端

    锁终端 输入: <1>cd /Applications/Xcode.app 回车 结果显示: Xcode.app 输入: <2>sudo chown -hR root:whee ...

  3. django 学习第一天搭建环境

    目前django版本是1.10,我学习的基础教材是 Web Development with Django Cookbook, Second Edition 搭建好配置环境 ssh免认证登录 修改一下 ...

  4. Git学习笔记一:新建本地仓库及初始化

    1.百度搜索Git下载安装,直接按默认选项安装即可. 例如:Git-2.7.2-32-bit_setup.1457942412.exe 2.配置Git信息,建立版本仓库 (Alt+PrintScerr ...

  5. Win10命令提示符(cmd)怎么复制粘贴

    在Win10系统里右键开始菜单,选择弹出菜单里的命令提示符,如下图所示: 然后复制要粘贴的文字,例如: echo hovertree.com 把上面的文字复制后,点击命令提示符窗口,然后在命令提示符窗 ...

  6. hive

    Hive Documentation https://cwiki.apache.org/confluence/display/Hive/Home 2016-12-22  14:52:41 ANTLR  ...

  7. PHP相关代码

    1 <html>  <head>       <meta http-equiv="content-type" content="text/h ...

  8. [转载]MVVM模式原理分析及实践

    没有找到很好的MVVM模式介绍文章,简单找了一篇,分享一下.MVVM实现了UI\UE设计师(Expression Blend 4设计界面)和软件工程师的合理分工,在SilverLight.WPF.Wi ...

  9. 分享一个与ABP配套使用的代码生成器源码

    点这里进入ABP系列文章总目录 分享一个与ABP配套使用的代码生成器源码 真对不起关注我博客的朋友, 因最近工作很忙, 很久没有更新博客了.以前答应把自用的代码生成器源码共享出来, 也一直没有时间整理 ...

  10. Javascript之匿名函数

    分析: 1.所谓匿名函数,从字面意思理解,就是没有名字的函数,js 用()来代替(注意,是英文状态下的括号) 2.定义形式: function (){ //to add codes that you ...