leetcode 5. Longest Palindromic Substring (java)

Posted eniac-inner

tags:

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

class Solution {
    public String longestPalindrome(String s) {
        if (s == null || s.length() < 1) return "";
        
        int start = 0;
        int end = 0;
        
        for (int i = 0; i < s.length(); i++) {
            int len1 = expandFromMiddle(s, i, i);
            int len2 = expandFromMiddle(s, i, i + 1);
            int len = Math.max(len1, len2);
            if (len > end - start) {
                start = i - ((len - 1) / 2);
                end = i + (len / 2);
            }
        }
        
        return s.substring(start, end + 1);
    }
    
    private int expandFromMiddle(String s, int left, int right) {
        if (s == null || left > right) return 0;
        
        while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {
            left--;
            right++;
        }
        
        return right - left - 1;
    }
}

  

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

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