銆怢eetCode銆?. Longest Palindromic Substring

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了銆怢eetCode銆?. Longest Palindromic Substring相关的知识,希望对你有一定的参考价值。

鏍囩锛?a href='http://www.mamicode.com/so/1/string' title='string'>string   log   code   link   inpu   longest   max   bst   private   

Difficulty: Medium

 More:銆愮洰褰曘€慙eetCode 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

浠庝笅鏍?寮€濮嬪線鏈熬閬嶅巻锛屽垽鏂互绗琲涓瓧绗︿负涓績锛屼互鍙婁互绗琲鍜岀i+1涓瓧绗︿箣闂翠负涓績鐨勬儏鍐碉紝鏍规嵁涓よ竟瀛楃鐩哥瓑鐨勬儏鍐佃繘琛宔xpand锛屼粠鑰岀‘瀹氭渶闀垮洖鏂囧瓙涓层€?/p>

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)銆?/p>

Space complexity :  O(1)

What I鈥榲e learned

1. 鍥炴枃瀛楃涓诧紝鎵惧埌涓績锛屽線宸﹀彸涓よ竟杩涜鍒ゆ柇銆?/p>

 

 More:銆愮洰褰曘€慙eetCode Java瀹炵幇

 

以上是关于銆怢eetCode銆?. Longest Palindromic Substring的主要内容,如果未能解决你的问题,请参考以下文章

銆怢eetCode鍒烽銆慡QL-Second Highest Salary 鍙婃墿灞曚互鍙奜racle涓殑鐢ㄦ硶

銆恖eetcode銆?8. 鍏ㄦ帓鍒?2

銆恖eetcode銆?534. 缁熻濂戒笁鍏冪粍

銆岄潰璇曞繀闂€峫eetcode楂橀棰樼簿閫?/a>

鍖楀ぇ绠楁硶澶х鐨凩eetCode鍒烽妯℃澘.pdf鏉ヤ簡锛?/h1>

銆怢inux銆慻it銆乺epo銆乻vn銆乤db浠ュ強鍏朵粬甯哥敤鍛戒护