Python 中的有效回文

pythonserver side programmingprogramming更新于 2025/10/27 0:12:17

假设我们有一个包含字母数字值和符号的字符串。其中也有小写字母和大写字母。我们必须通过仅考虑小写字母(大写字母将转换为小写字母)来检查字符串是否形成回文,其他符号(如逗号、空格)将被忽略。

假设字符串为"A Man, a Plan, a Canal: Panama",那么通过考虑这些规则,它将是"amanaplanacanalpanama"。这是一个回文。

要解决这个问题,请按照以下步骤 −

  • 定义 x = “”
  • 读取 str 中的每个字符 c −
    • 如果 c 是小写字母或数字,则将 c 附加到 x 中
    • 否则 c 是大写字母,则只需将其转换为小写并附加在 x 后面
  • 如果 x 是回文,则返回 True,否则返回 False

示例

让我们看看实现以获得更好的理解

class Solution(object):
   def isPalindrome(self, s):
      """
      :type s: str
      :rtype: bool
      """
      x = ""
      diff = ord('a') - ord('A')
      for i in s:
         if ord(i)>=ord('a') and ord(i)<=ord('z') or ord(i)>=ord("0") and ord(i)<=ord("9"):
            x+=i
         elif ord(i)>=ord('A') and ord(i)<=ord('Z'):
            i = chr(diff+ord(i))
            x+=i
      #print(s)
      #print(x)
      return x == x[::-1]
ob1 = Solution()
print(ob1.isPalindrome("A Man, a Plan, a Canal: Panama"))

输入

s = "A Man, a Plan, a Canal: Panama"

输出

true

相关文章


有用资源