1. 程式人生 > >LeetCode 最長迴文字串檢測

LeetCode 最長迴文字串檢測

寫了兩個方法,一個7000ms多一個5000ms多,比較菜,看了最厲害的50ms的程式碼,直接寫幾萬個字串做字典查詢,學不來學不來。。。。。。

import numpy as np

class Solution:
    def longestPalindrome2(self, s):
        """
        :type s: str
        :rtype: str
        """
        str_len = len(s)
        output_strs = list(s)
        for start_idx in range(str_len):
            biaoji = False
            for end_idx in range(str_len,start_idx-1, -1):
                temp = s[start_idx:end_idx]
                if temp==temp[::-1]:
                    output_strs.append(temp)
                    print(temp)
                    biaoji = True
                    break
            if biaoji:
                break
        if len(output_strs)==0:
            return ""
        str_lens = list(map(len, output_strs))
        return output_strs[np.argmax(str_lens)]

    def longestPalindrome(self, s):
        """
        :type s: str
        :rtype: str
        """
        str_len = len(s)
        max_len = 0
        result = ''
        for start_idx in range(str_len):
            for temp_len in range(str_len - start_idx, max_len - 1, -1):
                if temp_len <= max_len:
                    continue
                t = s[start_idx:start_idx + temp_len]
                if t == t[::-1]:
                    max_len = temp_len
                    result = t
                    break
        return result

if __name__ == '__main__':
    s = Solution()
    print(s.longestPalindrome("a"))