`

Leetcode - Longest Palindrome Substring

 
阅读更多
<div class="iteye-blog-content-contain" style="font-size: 14px"></div>
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.
[balabala] Method1从小到大逐一check不同长度的子串是否为回文,使用DP保存中间计算,但仍然会超时,Method3是非DP版的Method1,1年前的历史记录竟然是Accept的,估计当时leetcode 打瞌睡了。Method2 同样是DP,能够被Accept,分析计算次数和Method1一样,在Eclipse下实际运行超时的case,后者比前者快三、四ms,我认为差异主要是因为Method1 访问数组的模式不如Method2优,将二维数组看成一个矩阵,Method1 不断在各行间跳跃访问,而Method2 在一次外层循环中逐列访问同一行的数组。Method4是从当前1个字符或当前两个字符向两边辐射求得最长回文,该方法比Method2效率更高,因为它避免了一些无意义的计算,比如“abcdefg”, Method1和2均需要计算全部子串,而Method4不会计算诸如abcde这样的子串,在计算bcd时即停止计算其余以c为中心的子串。还有一种O(n)的实现,还未看懂,http://www.cnblogs.com/tenosdoit/p/3675788.html 先备忘着。

[ref]
http://www.cnblogs.com/tenosdoit/p/3675788.html
http://www.cnblogs.com/jdflyfly/p/3810674.html
http://codeganker.blogspot.com/2014/02/longest-palindromic-substring-leetcode.html

// Method 1: O(n^2), time out
    public String longestPalindrome1(String s) {
        if (s == null || s.equals(""))
            return "";
        int n = s.length();
        boolean[][] dp = new boolean[n][n];
        for (int i = 0; i < n; i++)
            dp[i][i] = true;
        String ans = s.substring(0, 1);
        for (int i = 0; i < n - 1; i++) {
            dp[i][i + 1] = s.charAt(i) == s.charAt(i + 1);
            if (ans.length() == 1 && dp[i][i + 1])
                ans = s.substring(i, i + 2);
        }
        
        for (int l = 3; l <= n; l++) {
            for (int i = 0; i + l <= n; i++) {
                int j = i + l - 1;
                dp[i][j] = s.charAt(i) == s.charAt(j) && dp[i + 1][j - 1];
                if (ans.length() < l && dp[i][j])
                    ans = s.substring(i, i + l);
            }
        }
        return ans;
    }
    
    // Method 2: O(n^2) 另一种DP实现
    // http://codeganker.blogspot.com/2014/02/longest-palindromic-substring-leetcode.html
    public String longestPalindrome(String s) {
        if (s == null || s.equals(""))
            return "";
        int n = s.length();
        String ans = "";
        int maxLen = 0;
        boolean[][] dp = new boolean[n][n];
        for (int i = n - 1; i >= 0; i--) {
            for (int j = i; j < n; j++) {
                if (s.charAt(i) == s.charAt(j) && (j - i < 2 || dp[i + 1][j - 1])) {
                    dp[i][j] = true;
                    if (maxLen < j - i + 1) {
                        maxLen = j - i + 1;
                        ans = s.substring(i, j + 1);
                    }
                }
            }
        }
        return ans;
    }
    
    // Method 3: O(n^2), from up to bottom, once accept, time out now
    public String longestPalindrome3(String s) {
        if (s == null || s.equals(""))
            return "";
        int n = s.length();
        for (int len = n; len >= 1; len--) {
            for (int i = 0; i + len <= n; i++) {
                String sub = s.substring(i, i + len);
                if (isPalin(sub)) {
                    return sub;
                }
            }
        }
        return "";
    }
    private boolean isPalin(String s) {
        int i = 0, j = s.length() - 1;
        while (i < j) {
            if (s.charAt(i) != s.charAt(j))
                return false;
            i++;
            j--;
        }
        return true;
    }
    
    // Method 4: O(n^2) 以当前字符或者当前字符及下一个字符向外辐射找出最长的子串
    // http://www.cnblogs.com/jdflyfly/p/3810674.html
    public String longestPalindrome4(String s) {
        if (s == null || s.equals(""))
            return "";
        int n = s.length();
        int maxLen = 1;
        int tmpLen = 0;
        String ans = s.substring(0, 1);
        for (int i = 0; i < n - 1; i++) {
            tmpLen = getPalin(s, i - 1, i + 1);
            if (tmpLen > maxLen) {
                int start = i - tmpLen / 2;
                ans = s.substring(start, start + tmpLen); 
                maxLen = tmpLen;
            }
            tmpLen = getPalin(s, i, i + 1);
            if (tmpLen > maxLen) {
                int start = i - tmpLen / 2 + 1;
                ans = s.substring(start, start + tmpLen);
                maxLen = tmpLen;
            }
        }
        return ans;
    }
    
    private int getPalin(String s, int left, int right) {
        int n = s.length();
        int len = right - left - 1;
        while (left >= 0 && right < n) {
            if (s.charAt(left--) == s.charAt(right++)) {
                len += 2;
            } else {
                return len;
            }
        }
        return len;
    }
分享到:
评论

相关推荐

    leetcode1-240题中文题解,md格式,java

    5. leetCode-5-Longest-Palindromic-Substring.md:第5题,最长回文子串,考察字符串处理和动态规划。 6. leetCode-84-Largest-Rectangle-in-Histogram.md:第84题,柱状图中最大的矩形,涉及到数组处理和栈的数据...

    LeetCode3 Longest Substring Without Repeating Characters

    Given a string, find the length of the longest substring without repeating characters. Examples: Given "abcabcbb", the answer is "abc", which the length is 3. Given "bbbbb", the answer is "b", with...

    gasstationleetcode-leetcode-rust:莱特代码休息

    3-longest-substring-without-repeating-characters 7 cargo run --bin 7-reverse-integer 9 cargo run --bin 9-palindrome-number 13 cargo run --bin 13-roman-to-integer 14 cargo run --bin 14-longest-common-...

    算法-leetcode-剑指offer上的题很多

    - **最长公共子串(Longest Common Substring)**: 在两个字符串中找到长度最长的相同子串。 - **字符串旋转(Rotate String)**: 将字符串进行旋转操作。 - **反转单词(Reverse Words)**: 将字符串中的单词顺序反转。 -...

    leetcode题库-LeetCode-Go:用GO回答LeetCode

    leetcode题库 LeetCode-Go 理论基础 见Note 脑图 TODO 待填充 算法题 面试高频出现,以及一些非常经典重要的算法题优先 题目列表 ...Longest Substring ...Longest ...Substring ...Palindrome Number 49.4% Easy

    机试高频考点.docx

    cn.com/problems/valid-palindrome/)、《有效的回文字符串 II》(https://leetcode-cn.com/problems/valid-palindrome-ii/)以及《最长回文子串》(https://leetcode-cn.com/problems/longest-palindromic-substring/)...

    分割数组求最大差值leetcode-Leetcode-Road:LeetCode刷题记录

    分割数组求最大差值leetcode ...Palindrome Number 56.7% 简单 10 Regular Expression Matching 25.3% 困难 11 Container With Most Water 59.3% 中等 12 Integer to Roman 61.8% 中等 13 Roman to In

    颜色分类leetcode-leetcode-[removed]我对Leetcode问题的解决方案

    Substring 最长回文子串 7 Reverse Integer 整数反转 9 Palindrome Number 回文数 11 Container With Most Water 盛最多水的容器 13 Roman to Integer 罗马数字转整数 14 Longest Common Prefix 最长公共前缀 20 ...

    lrucacheleetcode-leetcode-1:leetcode-1

    Palindrome Number 回文数字 10. Regular Expression Matching 动态规划,列出转换方程即可,注意初值 记T[i][j] = 是否S[0:i]和P[0:j]匹配 再分类讨论,其中pattern *分为0, 1, more三种类型 0: i不变, j+1

    leetcode实现strstr-leetcode-js:js刷leetcode

    Substring Without Repeating Characters 经典字符串,查找,哈希表,双指针法 2019/09/10 0004 Median of Two Sorted Arrays 二分查找,归并排序 2019/09/11 0006 ZigZag Conversion 逻辑 2019/09/13 0007 Reverse ...

    javalruleetcode-LeetCode:LeetCode算法问题

    Palindrome LeetCode 167 Two Sum II - Input array is sorted LeetCode 344 Reverse String LeetCode 345 Reverse Vowels of a String 2 字符串 编号 题目 LeetCode 3 Longest Substring Without Repeating ...

    lrucacheleetcode-leetcode:leetcodesolutionsinC++微信公众号:曲奇泡芙(互联网&智能汽车技术)

    ./0003-longest-substring-without-repeating-characters.cpp ./0004-median-of-two-sorted-arrays.cpp ./0005-longest-palindromic-substring.cpp ./0006-zigzag-conversion.cpp ./0007-reverse-integer.cpp ./0008...

    LeetCode-Feb2021

    动态规划是解决复杂问题的利器,如"Longest Increasing Subsequence"(最长递增子序列)问题。Java中动态规划的实现通常涉及二维或一维数组,关键在于设计状态转移方程。 五、贪心算法 贪心算法在解决部分最优问题...

    LeetCode最全代码

    # [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python%20%2F%20C++%2011-orange.svg) [![License]...

    算法刷题笔记leetcode/lintcode

    - Longest Palindromic Substring(最长回文子串) - Space Replacement(URL化) - Wildcard Matching(通配符匹配) - Length of Last Word(最后一个单词的长度) - Count and Say(猜数字序列) - **...

    leetcode338-LeetCode:LeetCode刷题总结

    LeetCode刷题总结 1.Two Sum 2.Add Two Numbers 3.Longest Substring Without Repeating Characters 4.Median of Two Sorted Arrays 5.Longest Palindromic Substring (Manacher算法待完成) 6.ZigZag Conversion 7....

    leetcode卡-LeetCode:LeetCode题解

    Palindrome :star: 有效回文,小写字母转换 0005 Longest Palindromic Substring :star: :star: :star: 最长回文子串,Manacher算法 0010 RegularExpressionMatching :star: :star: :star: 正则表达式匹配,dp 0012 ...

    leetcode分类-LeetCode:力码

    leetcode ...Substring Interleaving String Triangle Distinct Subsequences Decode Ways Palindrome Partitioning II Maximal Rectangle ###Recursion N-Queens N-Queens II Balanced Binary Tree Binar

    997leetcodec-myleetcode:我的leetcode解决方案

    5-longest-palindromic-substring.c。 (完毕) 使用优化算法更新 214-shortest-palindrome.c。 使用二分搜索更新 287-find-the-duplicate-number.c 和弗洛伊德的龟兔赛跑(循环检测)算法。 (完毕) 使用哈希表...

    leetcode题库-LeetCode:力码

    Palindrome Number.cpp 12 整数转罗马数字 Integer to Roman.cpp 13 罗马数字转整数 Roman to Integer.cpp 15 三数之和 3Sum.cpp 最接近的三数之和 3Sum Closest .cpp 20 有效的括号 Valid Parentheses.cpp 22 括号...

Global site tag (gtag.js) - Google Analytics