2023年9月13日 星期三

9/13 每日一題(尋找最長回文)

Given a string s, return the longest 

 

 in s.

 

Example 1:

Input: s = "babad"
Output: "bab"
Explanation: "aba" is also a valid answer.

Example 2:

Input: s = "cbbd"
Output: "bb"

 

Constraints:

  • 1 <= s.length <= 1000
  • s consist of only digits and English letters.


 class Solution:

    def longestPalindrome(self, s: str) -> str:
        n=0
        long=len(s)
        while long > 0:
            tes_list=s[n:n+long]
            if tes_list == tes_list[::-1] :
                print(f'抓到回文')
                print(tes_list)
                return "".join(tes_list)
            n+=1
            if n+long>len(s):
                '初始化, 進入下一輪'
                long -= 1
                n = 0
           
--------------------------------
class Solution:
    def longestPalindrome(self, s: str) -> str:
        if s == s[::-1]:
            return s
        start, size = 0, 1
        for i in range(1, len(s)):
            l, r = i - size, i + 1
            s1, s2 = s[l-1:r], s[l:r]
            if l >= 1 and s1 == s1[::-1]:
                size += 2
                start = l - 1
            elif s2 == s2[::-1]:
                size += 1
                start = l
        return s[start: start + size]
       
       
       
           

標籤:

0 個意見:

張貼留言

訂閱 張貼留言 [Atom]

<< 首頁