Leetcode 0005: Longest Palindromic Substring

题目描述:

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. 枚举数组中的每个位置i,从当前位置开始向两边扩散,
  2. 当回文子串长度是奇数时,从i开始往两边扩散,
  3. 当回文子串长度是偶数时,从i,i + 1开始往两边扩散
  4. start 存储当前最长回文子串的起始指针,end 存储当前最长回文子串的末尾指针,每次扩散后若存在回文子串比以前的长,以及两端的位置start和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;
        }
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_43946031/article/details/113798830