【Java】【LeetCode】5. 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.

Example 1:

Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.

Example 2:

Input: "cbbd"
Output: "bb"

题解

是对于每个子串的中心(可以是一个字符,或者是两个字符的间隙,比如串abc,中心可以是a,b,c,或者是ab的间隙,bc的间隙,例如aba是回文,abba也是回文,这两种情况要分情况考虑)往两边同时进 行扫描,直到不是回文串为止。假设字符串的长度为n,那么中心的个数为2*n-1(字符作为中心有n个,间隙有n-1个)。对于每个中心往两边扫描的复杂 度为O(n),所以时间复杂度为O((2*n-1)*n)=O(n^2),空间复杂度为O(1)。

代码如下:

public static String longestPalindrome(String s) {
        if (s == null || s.length() <= 1) {
            return s;
        }
        String result = "";
        for (int i = 0; i < s.length(); i++) {
            // get longest palindrome with center of i
            String tmp = findPalindrome(s, i, i);
            result = tmp.length() > result.length() ? tmp : result;
            // get longest palindrome with center of i, i+1
            tmp = findPalindrome(s, i, i + 1);
            result = tmp.length() > result.length() ? tmp : result;
        }
        return result;
    }

    // Given a center, either one letter or two letter,Find longest palindrome
    public static String findPalindrome(String s, int i, int j) {
        while (i >= 0 && j <= s.length() - 1 && s.charAt(i) == s.charAt(j)) {
            i--;
            j++;
        }
        return s.substring(i + 1, j);
    }

你可能感兴趣的:(LeetCode,Algorithm)