java 5.最长的Palindromic Substring.java

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 5.最长的Palindromic Substring.java相关的知识,希望对你有一定的参考价值。

class Solution(object):
    def longestPalindrome(self, s):
        """
        :type s: str
        :rtype: str
        """
        if not s:
            return '';
        
        # Use dynamic programming
        dp = [[False for i in range(len(s))] for i in range(len(s))];
        # define dp[i][j] is whether subtring from i to j is palindrome or not 
        
        maxlength = 0;
        res = ""
        
        for i in range(len(s) - 1, -1,-1):
            for j in range(i,len(s)):
                if s[i] == s[j] and ( j - i <= 2 or dp[i + 1][j - 1]) :
                    dp[i][j] = True;
                    
                    
                    if j - i + 1 > maxlength:
                        maxlength = j - i + 1;
                        res = s[i : j + 1];
        
        return res;
public class Solution {
    public String longestPalindrome(String s) {
        
        String res = "";
        int resLen = 0;
        
        int len = s.length();
        int[][] dp = new int[len][len];
        
        for(int i = len - 1; i >= 0; i--){
            for(int j = i; j < len; j++){
                if(s.charAt(i) == s.charAt(j) && (j - i < 2 || dp[i + 1][j - 1] == 1)){
                    ////先判断 j - i < 2,否则 i = j = len - 1 时下标溢出
                    dp[i][j] = 1;
                    
                    if(j - i + 1 >= resLen){ //"abcd" the answer is "a"!!!!!
                        resLen = j - i + 1;
                        res = s.substring(i, j + 1);
                    }
                }
            }
        }
        return res;
    }
}

以上是关于java 5.最长的Palindromic Substring.java的主要内容,如果未能解决你的问题,请参考以下文章

java 5.最长的Palindromic Substring.java

java 5.最长的Palindromic Substring.java

java 5.最长的Palindromic Substring.java

java 5.最长的Palindromic Substring.java

leetcode longest palindromic substring (medium) /java

LeetCode第[5]题(Java):Longest Palindromic Substring 标签:String动态规划