1. 程式人生 > >【LeetCode】5. Longest Palindromic Substring

【LeetCode】5. Longest Palindromic Substring

bad leetcode subst sta desc null html fin als

Difficulty: Medium

More:【目錄】LeetCode Java實現

Description

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"

Intuition

從下標0開始往末尾遍歷,判斷以第i個字符為中心,以及以第i和第i+1個字符之間為中心的情況,根據兩邊字符相等的情況進行expand,從而確定最長回文子串。

Solution

    public String longestPalindrome(String s) {
        if(s==null || s.length()<=0)
            return s;
        int start=0;
        int end=0;
        for(int i=0;i<s.length();i++){
            int len1=expand(s,i,i);
            int len2=expand(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 expand(String s,int l,int r){
        while(l>=0 && r<s.length() && s.charAt(l)==s.charAt(r)){
            l--;
            r++;
        }
        return r-l-1;
    }

  

Complexity

Time complexity : O(n^2)

  需要遍歷n個字符,每次判斷的復雜度為O(n)。

Space complexity : O(1)

What I‘ve learned

1. 回文字符串,找到中心,往左右兩邊進行判斷。

More:【目錄】LeetCode Java實現

【LeetCode】5. Longest Palindromic Substring