leetcode--5. Longest Palindromic Substring

Posted 戎码之路

tags:

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

题目来自 https://leetcode.com/problems/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.

  给一个字符串S,在S中找出最长回文子字符串。你可以设置字符串的最大长度为1000,这里面存着一个唯一的最长回文字符串。

方法1:

以中心对称的方法检测回文

public class LongestPalindromicSubstring {
    public static String expendCenterStr(String s,int r,int l){
        if (s.length()==0){
            return "";
        }
        int n=s.length();
        while (r>=0&&l<n&&s.charAt(r)==s.charAt(l)){
            r--;
            l++;
        }
        return s.substring(r+1,l);
    }

    public static String longestPalindrome(String s) {

        String longestStr=s.substring(0,1);
        for (int i=0;i<s.length();i++){
            String s1=expendCenterStr(s,i,i);
            if (s1.length()>longestStr.length()){
                longestStr=s1;
            }
            String s2=expendCenterStr(s,i,i+1);
            if (s2.length()>longestStr.length()){
                longestStr=s2;
            }
        }
        return longestStr;
    }

    public static void main(String[] args) {
        System.out.println(longestPalindrome("ffasfgcabbacgdsfs"));
    }
}

 

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

leetcode--5. Longest Palindromic Substring

#Leetcode# 5. Longest Palindromic Substring

[LeetCode] 5 Longest Palindromic Substring

Leetcode #5. Longest Palindromic Substring

LeetCode 5_Longest Palindromic Substring

[leetcode][5] Longest Palindromic Substring