A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.
Given a string
s
, return true
if it is a palindrome, or false
otherwise.Example 1:
Input: s = “A man, a plan, a canal: Panama”
Output: true
Explanation: “amanaplanacanalpanama” is a palindrome.
Example 2:
Input: s = “race a car”
Output: false
Explanation: “raceacar” is not a palindrome.
Example 3:
Input: s = “ “
Output: true
Explanation: s is an empty string “” after removing non-alphanumeric characters.
Since an empty string reads the same forward and backward, it is a palindrome.
Constraints:
`1 <= s.length <= 2 105
*
s` consists only of printable ASCII characters.题目大意:
求含非字母数字的字符串是否回文,字符串含空格,冒号等. Easy题
双指针解题思路(推荐):
回文首先考虑用相向双指针
解题步骤:
N/A
注意事项:
- 比较时,要转换成小写
- 外循环left < right条件要复制到内循环中
Python代码:
1 | def isPalindrome(self, s: str) -> bool: |
算法分析:
时间复杂度为O(n)
,空间复杂度O(1)
reverse法算法II解题思路:
reverse字符串比较
注意事项:
- 比较时,要转换成小写
Python代码:
1 | def isPalindrome2(self, s: str) -> bool: |
算法分析:
时间复杂度为O(n)
,空间复杂度O(n)