【LeetCode】5. Longest Palindromic Substring

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实现

 

posted @ 2018-12-10 21:01  华仔要长胖  阅读(182)  评论(0编辑  收藏  举报