编码挑战是提高编程技能、参与社区和学习新技术的绝佳方式。在这篇博文中,我们将提出一个编码挑战,讨论解决该问题的各种方法,并邀请读者在评论中分享他们的解决方案。让我们潜入吧!
问题:
给定一个字符串 s,找到 s 中最长的回文子串。回文是向后读与向前读相同的字符串。
示例:
Input: s = "babad" Output: "bab" Note: "aba" is also a valid answer.
约束:
在进入代码之前,请确保您理解问题。回文子串是向后读与向前读相同的字符序列。我们的目标是找到给定字符串 s 中最长的子字符串。
有多种方法可以解决这个问题。我们将讨论三种方法:
蛮力方法涉及检查所有可能的子字符串并确定它们是否是回文。这种方法很简单,但对于大字符串来说效率不高。
def longest_palindrome_brute_force(s): def is_palindrome(sub): return sub == sub[::-1] n = len(s) longest = "" for i in range(n): for j in range(i, n): if is_palindrome(s[i:j+1]) and len(s[i:j+1]) > len(longest): longest = s[i:j+1] return longest print(longest_palindrome_brute_force("babad")) # Output: "bab" or "aba"
这种方法涉及围绕每个字符(以及字符之间)进行扩展以找到最长的回文。它比蛮力更有效率。
def longest_palindrome_expand_center(s): 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] longest = "" for i in range(len(s)): # Odd length palindromes odd_palindrome = expand_around_center(i, i) if len(odd_palindrome) > len(longest): longest = odd_palindrome # Even length palindromes even_palindrome = expand_around_center(i, i+1) if len(even_palindrome) > len(longest): longest = even_palindrome return longest print(longest_palindrome_expand_center("babad")) # Output: "bab" or "aba"
动态规划方法使用表来存储子串是否是回文,从而获得高效的解决方案。
def longest_palindrome_dp(s): n = len(s) if n == 0: return "" dp = [[False] * n for _ in range(n)] start, max_length = 0, 1 for i in range(n): dp[i][i] = True for length in range(2, n+1): for i in range(n-length+1): j = i + length - 1 if s[i] == s[j]: if length == 2 or dp[i+1][j-1]: dp[i][j] = True if length > max_length: start = i max_length = length return s[start:start+max_length] print(longest_palindrome_dp("babad")) # Output: "bab" or "aba"
以上是编码挑战:通过解决问题参与和学习的详细内容。更多信息请关注PHP中文网其他相关文章!