# 题目

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. Angular杂谈系列1-如何在Angular2中使用jQuery及其插件

    jQuery,让我们对dom的操作更加便捷.由于其易用性和可扩展性,jQuer也迅速风靡全球,各种插件也是目不暇接. 我相信很多人并不能直接远离jQuery去做前端,因为它太好用了,我们以前做的东西大 ...

  2. C语言 · 4-3水仙花数

    问题描述 打印所有100至999之间的水仙花数.所谓水仙花数是指满足其各位数字立方和为该数字本身的整数,例如 153=1^3+5^3+3^3. 样例输入 一个满足题目要求的输入范例.例:无 样例输出 ...

  3. [Java 缓存] Java Cache之 DCache的简单应用.

    前言 上次总结了下本地缓存Guava Cache的简单应用, 这次来继续说下项目中使用的DCache的简单使用. 这里分为几部分进行总结, 1)DCache介绍; 2)DCache配置及使用; 3)使 ...

  4. 前端自动化构建工具gulp记录

    一.安装 1)安装nodejs 通过nodejs的npm安装gulp,插件也可以通过npm安装.windows系统是个.msi工具,只要一直下一步即可,软件会自动在写入环境变量中,这样就能在cmd命令 ...

  5. 深入学习jQuery自定义插件

    原文地址:jQuery自定义插件学习 1.定义插件的方法 对象级别的插件扩展,即为jQuery类的实例增加方法, 调用:$(选择器).函数名(参数);      $(‘#id’).myPlugin(o ...

  6. Ajax部分

    Ajax的概念 AJAX即"Asynchronous Javascript And XML"(异步JavaScript和XML),是一种用于创建快速动态网页的技术. 动态网页:是指 ...

  7. 5.0 JS中引用类型介绍

    其实,在前面的"js的六大数据类型"文章中稍微说了一下引用类型.前面我们说到js中有六大数据类型(五种基本数据类型 + 一种引用类型).下面的章节中,我们将详细讲解引用类型. 1. ...

  8. vue.js几行实现的简单的todo list

    序:目前前端框架如:vue.react.angular,构建工具fis3.gulp.webpack等等...... 可谓是五花八门,层出不穷,眼花缭乱...其实吧只要你想玩还是可以玩玩的..下面是看了 ...

  9. 编译器开发系列--Ocelot语言4.类型定义的检查

    这里主要介绍一下检查循环定义的结构体.联合体.是对成员中包含自己本身的结构体.联合体进行检查.所谓"成员中包含自己本身",举例来说,就是指下面这样的定义. struct point ...

  10. 简述我的SOA服务治理

    SOA服务治理 1.解决业务部门服务冲突和纠纷2.版本定义与版本管理3.服务备案与服务管理4.业务监督与服务监控 SOA的战略目的 一.业务价值胜过技术策略 二.战略目标胜过具体项目的效益 三.内置的 ...