Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Palindrome hợp lệ trong Python


Cho chuỗi alphanumeric và ký tự đặc biệt. Kiểm tra palindrome chỉ xét chữ cái thường (chữ hoa chuyển thành thường), bỏ qua ký tự khác. Ví dụ: "A Man, a Plan, a Canal: Panama" → "amanaplanacanalpanama" → true.

Giải pháp

Lọc ký tự:

  • x = "".
  • Duyệt s: nếu là chữ thường hoặc số → thêm vào x; nếu chữ hoa → chuyển thường thêm vào x.
  • Kiểm tra x == x[::-1].

Ví dụ

Triển khai Python:

class Solution(object): 
    def isPalindrome(self, s): 
        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 
        return x == x[::-1] 
ob1 = Solution() 
print(ob1.isPalindrome("A Man, a Plan, a Canal: Panama"))

Đầu vào

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

Đầu ra

true