题目描述:
给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。
说明:本题中,我们将空字符串定义为有效的回文串。
示例 1:
输入: "A man, a plan, a canal: Panama"
输出: true
示例 2:
输入: "race a car"
输出: false
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/valid-palindrome
代码实现:
1 def isPalindrome(s): 2 ''' 3 验证是否为回文串 4 :param str: 5 :return: 6 ''' 7 8 code = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", 9 "v", "w", "x", "y", "z"] 10 CODE = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", 11 "V", "W", "X", "Y", "Z"] 12 num = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"] 13 string = "" 14 for ch in s: 15 if ch in code: 16 string += ch 17 elif ch in CODE: 18 string += code[CODE.index(ch)] 19 elif ch in num: 20 string += ch 21 22 print("string=", string) 23 if string.isspace() or len(string) == 0: 24 return True 25 26 left, right = 0, len(string) - 1 27 while left < right: 28 if string[left] == string[right]: 29 left += 1 30 right -= 1 31 else: 32 return False 33 34 return True 35 36 37 print("------测试isHuiwen--------") 38 s = "aaaa" 39 print(isPalindrome(s)) 40 41 42 def isPalindrome1(s): 43 ''' 44 反转字符串来判断 45 :param s: 46 :return: 47 ''' 48 # isalnum() 方法检测字符串是否由字母和数字组成。 49 sgood = "".join(ch.lower() for ch in s if ch.isalnum()) 50 return sgood == sgood[::-1] 51 # return tmps == tmps[::-1] 52 53 54 print("------测试isHuiwen--------") 55 s = "A man, a plan, a canal: Panama" 56 print(isPalindrome1(s)) 57 58 59 def isPalindromel2(s): 60 ''' 61 双指针判断 62 :param s: 63 :return: 64 ''' 65 tmps = "" 66 for ch in s: 67 if ch.isalnum(): 68 tmps += ch.lower() 69 70 print("tmps=", tmps) 71 left, right = 0, len(tmps) - 1 72 while left < right: 73 if tmps[left] == tmps[right]: 74 left += 1 75 right -= 1 76 else: 77 return False 78 79 return True 80 81 82 print("------测试isHuiwen2--------") 83 s = "s " 84 print(isPalindromel2(s)) 85 86 87 def isPalinedrome3(s): 88 left, right = 0, len(s) - 1 89 while left < right: 90 if s[left].isalnum() == True and s[right].isalnum() == True: 91 if s[left].lower() == s[right].lower(): 92 left += 1 93 right -= 1 94 else: 95 return False 96 elif s[left].isalnum() == True and s[right].isalnum() == False: 97 right -= 1 98 elif s[left].isalnum() == False and s[right].isalnum() == True: 99 left += 1 100 else: 101 left += 1 102 right -= 1 103 104 return True 105 106 107 print("------测试isHuiwen3--------") 108 s = " " 109 print(isPalinedrome3(s))
输出:
------测试isHuiwen-------- string= aaaa True ------测试isHuiwen-------- True ------测试isHuiwen2-------- tmps= s True ------测试isHuiwen3-------- True
总结:双指针法和字符串反转直接判断两种方法。isalnum()函数判断字符是否为数字或者字母。字符串的反转操作[::-1]