Java最長迴文串

在Java中,可以使用以下方法來找到最長的迴文串:

public static String findLongestPalindrome(String str) {
    int n = str.length();
    int maxLen = 1;
    int start = 0;
    for (int i = 0; i < n; i++) {
        int j = i + maxLen;
        while (j < n && str.charAt(i) == str.charAt(j)) {
            j++;
            maxLen++;
        }
        if (maxLen > 1) {
            start = i;
        }
        while (j > i && j - i > maxLen / 2 && str.charAt(i) == str.charAt(j - 1)) {
            maxLen--;
            j--;
        }
        if (maxLen > 1) {
            start = i;
        }
    }
    return str.substring(start, start + maxLen);
}

這個方法使用迴圈來遍歷字元串的每一個字元,並檢查其是否為迴文串。如果發現一個比之前找到的更長的迴文串,則更新最長迴文串的長度和起始位置。

請注意,這個方法假設字元串str已經被轉換為小寫,並且不包含任何非字母字元。如果字元串中包含非字母字元,則需要先進行處理,例如使用正則表達式來去除這些字元。