【LeetCode】5. Longest Palindromic Substring

Difficulty: Medium

 More:【目錄】LeetCode Java實現html

Description

Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.java

Example 1:post

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

Example 2:ui

Input: "cbbd"
Output: "bb"

Intuition

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

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)blog

  須要遍歷n個字符,每次判斷的複雜度爲O(n)。ip

Space complexity :  O(1)字符串

What I've learned

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

 

 More:【目錄】LeetCode Java實現string

相關文章
相關標籤/搜索