【问题标题】:Checking a string if it is a valid palindrome or not using python3使用python3检查字符串是否是有效的回文
【发布时间】:2021-10-22 22:35:06
【问题描述】:
class Solution:
    def isPalindrome(self, s: str) -> bool:
        string=''
        ss=s.lower()
        
        for x in ss:
            if x.isalnum():
                string.join(x)
        bol= string == string[::-1]
                
        return bol
str_1="A man, a plan, a canal: Panama"  
str_2="race a car"  

对于 str_1,代码工作正常(输出为 TRUE),但对于 str_2,输出也为 TRUE,但它不是回文。 我无法理解我的代码中的错误。

【问题讨论】:

    标签: python arrays python-3.x string palindrome


    【解决方案1】:

    给定一个字符串,编写一个python函数来检查它是否是回文。如果字符串的反转与字符串相同,则称该字符串为回文。例如,“radar”是回文,但“radix”不是回文。

    def isPalindrome(s):
        return s == s[::-1]    
     
    # Driver code
    s = "hello"
    ans = isPalindrome(s)
     
    if ans:
        print("Yes")
    else:
        print("No")
    

    【讨论】:

      【解决方案2】:

      因为你不是每次加入字符串时都保存。

      class Solution:
          def isPalindrome(self, s: str) -> bool:
              string=''
              ss=s.lower()
              
              for x in ss:
                  if x.isalnum():
                      string += ''.join(x) # Remember to save the new added character
              bol= string == string[::-1]
                      
              return bol
      

      【讨论】:

        【解决方案3】:

        试试这个:

        class Solution:
            def isPalindrome(self, s: str) -> bool:
                string=""
                ss=s.lower()
                
                string = ''.join(x for x in ss if x.isalnum())    
                
                bol= string == string[::-1]
                        
                return bol
        

        输出:

        #for str_1
        True
        # for str_2
        False
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2013-02-13
          • 1970-01-01
          • 2018-04-07
          • 1970-01-01
          • 1970-01-01
          • 2020-03-15
          • 2019-05-05
          相关资源
          最近更新 更多