Study Plan For Algorithms - Part3

1.最长回文子串
给定一个字符串 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 字形变换
将一个给定字符串 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)
posted @ 2024-08-17 23:32  WindMay  阅读(1)  评论(0编辑  收藏  举报