解法比较简单:
两个指针,分别从左向右,从右向左遍历字符串,时间复杂度,空间复杂度
。
Python源码:
class Solution:
def isPalindrome(self, s: str) -> bool:
s = s.lower()
left_p = 0
right_p = len(s) - 1
while(left_p < right_p):
while((not s[left_p].isalpha()) and (not s[left_p].isdigit()) and left_p < right_p):
left_p += 1
while((not s[right_p].isalpha()) and (not s[right_p].isdigit()) and right_p > left_p):
right_p -= 1
if s[left_p].lower() != s[right_p].lower():
return False
left_p += 1
right_p -= 1
return True
我的心路:
标准解法和我的思路相同,但在实现过程中,数字未考虑、while循环忘记判断左右指针合法情况,花费了一些时间。简洁性在看他人代码时得到优化。
另外很奇怪,not(A or B)会报错,只好改回(not A and not B)