【LeetCode 5. Longest Palindromic Substring】

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"

翻譯

給定一個字符串 s,找到 s 中最長的迴文子串(正讀和反讀都相同的字符串)。你可以假設 s 的最大長度爲 1000。

分析

由於迴文串是對稱的,所以每次循環選擇一箇中心,進行左右擴展,判斷左右字符是否相等即可。字符串所含有字母數存在是奇數或者偶數,所以需要從一個字符開始擴展,或者從兩個字符之間開始擴展,所以總共有 2n-1 (n+n-1)箇中心。


Kotlin代碼實現:

public String longestPalindrome(String s) {
    if (s == null || s.length() < 1) return "";
    int start = 0, end = 0;
    for (int i = 0; i < s.length(); i++) {
        int len1 = expandAroundCenter(s, i, i);
        int len2 = expandAroundCenter(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 expandAroundCenter(String s, int left, int right) {
    int leftIndex = left, rightIndex = right;
    while (leftIndex >= 0 && rightIndex < s.length() && s.charAt(leftIndex) == s.charAt(rightIndex)) {
        leftIndex --;
        rightIndex ++;
    }
    return rightIndex - leftIndex - 1;
}

參考:
https://leetcode.com/problems/longest-palindromic-substring

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章