5. [M] Longest Palindromic Substring

https://leetcode.com/problems/longest-palindromic-substring/

中心扩展法

对于每个字符,以其为中心向两边展开、比对,直到遇到不同字符。中心分两种情况,一种是单字符,一种是双字符。

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

时间复杂度 O(n^2),空间复杂度 O(1)

动态规划

// Ain't no code for that yet, sorry

最后更新于

这有帮助吗?