The title leetcode longest substring palindromic

Subject description:

Given a string s, s to find the longest substring palindromic. You can assume that the maximum length of 1000 s.

Example 1:

Enter: "babad"
Output: "bab"
Note: "aba" is a valid answer.
Example 2:

Enter: "cbbd"
Output: "bb"

Solution one: Addons, flowering Center

We know that certain palindromic sequence is symmetric, so we can select a center of each cycle, for about expansion, it determines whether the character is equal to about.

                                                    

Because the string and the even-odd character string is present, so we need to start from the extension of a character or two characters from the extended between, so a total of n + n-1 centers.

{Solution class 
    
   public static String longestPalindrome (String S) { 
        IF (S == null || s.length () == 0) { 
            return ""; 
        } 
        // record start position of the palindromic sequence 
        int Start = 0; 
        / / recording end position of the palindromic sequence 
        int end = 0; 
        // record length of palindromic sequence obtained intermediate 
        int maxLen = 0; 
        for (int I = 0; I <s.length (); I ++) { 
            // from n + n-1 center points begin to spread 
            int LEN1 getTheLengthOfPalindrome = (S, I, I); 
            int LEN2 getTheLengthOfPalindrome = (S, I, I +. 1); 
            maxLen = Math.max (LEN1, LEN2); 
            IF (maxLen> (End - Start)) { 
                Start = I - (maxLen -. 1) / 2;
                = I + maxLen End / 2; 
            } 
        } 
        // Note here: subString two parameters: start palindromic sequence start character, end to end of the palindromic sequence index -1 
        return s.substring (Start, end +. 1); 
    } 

    Private static int getTheLengthOfPalindrome (S String, int left, int right) { 

        int L = left; 
        int right = R & lt; 
        the while (L> = 0 && R & lt <s.length () && s.charAt (L) == S .charAt (R & lt)) { 
            L -; 
            R & lt ++; 
        } 
        // End extended string length palindromic (R-1) - (L + 1) +1, it is. 1-L-R & lt 
        return R & lt -. 1 - L; 
    } 
}

Complexity analysis:

~ Time complexity: O (N²)

~ Spatial complexity: O (. 1)

Guess you like

Origin www.cnblogs.com/ysw-go/p/11420535.html