面試題:字符串最長迴文

迴文:正數和倒數相同。如sos,level。

現在給定字符串“er0reviver”要求給出字符串內最長的迴文。寫出代碼輸出結果。

Java:

public static String longestPalindrome(String str) {
        int length = str.toCharArray().length;
        int resultLength = 0;
        String result = null;
        for (int i = 0; i < length - 1; i++) {
            for (int j = i + 1; j < length; j ++) {
                boolean palindrome = isPalindrome(str, i, j);
                int subLength = j - i + 1;
                if (palindrome && subLength > resultLength) {
                    resultLength = subLength;
                    result = str.substring(i, j + 1);
                }
            }
        }
        return result;
    }

    private static boolean isPalindrome(String str, int start, int end) {
        char[] chars = str.toCharArray();
        for (int i = start, j = end; i < j; i++, j--) {
            if (chars[i] != chars[j]) {
                return false;
            }
        }
        return true;
    }

Python:

def isPalindrome(s, start, end):
    while start < end:
        if s[start] != s[end]:
            return flase
        start += 1
        end -= 1
    return true

def longestPalindrome(s):
    max, left, right =0, 0, 0
    for i in range(len(s)):
    j = i + 1
    while j < len(s):
        if (isPalindrome, i, j):
            if (j - i + 1) > max:
                left, right = i, j
                max = j - i + 1
        j += 1
    return s[left:right + 1]

時間複雜度:n * logn

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