Leetcode 0005: Longest Palindromic Substring

Title description:

Given a string s, return the longest palindromic substring in s.

Example 1:

Input: s = “babad”
Output: “bab”
Note: “aba” is also a valid answer.

Example 2:

Input: s = “cbbd”
Output: “bb”

Example 3:

Input: s = “a”
Output: “a”

Example 4:

Input: s = “ac”
Output: “a”

Constraints:

1 <= s.length <= 1000
s consist of only digits and English letters (lower-case and/or upper-case),

Time complexity: O ( n 2 )   \Omicron(n^{2})\, O ( n2)

  1. Enumerate each position i in the array, starting from the current position and spreading to both sides,
  2. When the length of the palindrome substring is odd, it starts from i and spreads to both sides,
  3. When the length of the palindrome substring is even, start from i, i + 1 and spread to both sides
  4. start stores the start pointer of the current longest palindrome substring, end stores the end pointer of the current longest palindrome substring, if there is a palindrome substring longer than the previous one after each diffusion, and the positions of the two ends start and end
class Solution {
    
    
    // 1. set center 
    // 2. left <- center -> right check 
    int start, end;
    public String longestPalindrome(String s) {
    
    
        if (s == null || s.length() < 1) return "";
        int n = s.length();
        for(int i = 0; i < n; i++){
    
    
            // check odd
            helper(s, i-1, i+1);
            // check even
            helper(s, i, i+1);
        }
        return s.substring(start+1, end);
    }

    private void helper(String s, int left, int right){
    
    
        int l = left;
        int r = right;
        while(l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)){
    
    
            l--;
            r++;
        }
        if(end - start < r - l){
    
    
            start = l;
            end = r;
        }
    }
}

Guess you like

Origin blog.csdn.net/weixin_43946031/article/details/113798830