Study Plan For Algorithms - Part3

WindMay發表於2024-08-17

1.最長迴文子串
題目連結:https://leetcode.cn/problems/longest-palindromic-substringm/
給定一個字串 s,找到 s 中最長的 迴文 子串

class Solution:
    def longestPalindrome(self, s: str) -> str:
        def expand_around_center(left, right):
            while left >= 0 and right < len(s) and s[left] == s[right]:
                left -= 1
                right += 1
            return s[left + 1:right]        
            
        res = ""
        for i in range(len(s)):
            palindrome1 = expand_around_center(i, i)
            palindrome2 = expand_around_center(i, i + 1)
            if len(palindrome1) > len(res):
                res = palindrome1
            if len(palindrome2) > len(res):
                res = palindrome2
        return res

2.Z 字形變換
題目連結:https://leetcode.cn/problems/zigzag-conversion/
將一個給定字串 s 根據給定的行數 numRows ,以從上往下、從左到右進行 Z 字形排列。

class Solution:
    def convert(self, s: str, numRows: int) -> str:
        if numRows == 1 or numRows >= len(s):
            return s

        rows = ['' for _ in range(numRows)]
        index, step = 0, 1

        for char in s:
            rows[index] += char
            if index == 0:
                step = 1
            elif index == numRows - 1:
                step = -1
            index += step

        return ''.join(rows)

相關文章