算法题--判断字符串是否合法回文
2020-05-04 本文已影响0人
岁月如歌2020
image.png
0. 链接
1. 题目
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
Note: For the purpose of this problem, we define empty string as valid palindrome.
Example 1:
Input: "A man, a plan, a canal: Panama"
Output: true
Example 2:
Input: "race a car"
Output: false
2. 思路1: 双指针
- 基本思路是用两个指针left和right, left从左至右, right从右至左, 逐对判断s[left]是否和s[right]表示同一个字符, 直到left和right相遇
- 时间复杂度: ```O(N)``
- 空间复杂度:
O(1)
3. 代码
# coding:utf8
class Solution:
def isPalindrome(self, s: str) -> bool:
left = 0
right = len(s) - 1
while left < right:
while left < right and not s[left].isalnum():
left += 1
while right > left and not s[right].isalnum():
right -= 1
if s[left].lower() != s[right].lower():
return False
else:
left += 1
right -= 1
return True
def my_test(solution, s):
print('input: {}; output: {}'.format(s, solution.isPalindrome(s)))
solution = Solution()
my_test(solution, 'A man, a plan, a canal: Panama')
my_test(solution, 'race a car')
my_test(solution, ' ')
my_test(solution, '0P')
输出结果
input: A man, a plan, a canal: Panama; output: True
input: race a car; output: False
input: ; output: True
input: 0P; output: False