题目描述
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
解题思路1: 头尾指针
这个题目思路很简单, 使用前后双指针, 遍历字符串数组, 判断是否相等. (注意跳过非字符数字, 这里我们使用系统的方法isLetter和isNumber进行判断)
时间复杂度: O(n)
示例代码1:
func isPalindrome(_ s: String) -> Bool {
if s.isEmpty {
return true
}
let tempArr = Array(s)
var i = 0
var j = tempArr.count - 1
while i < j {
if !(tempArr[i].isLetter || tempArr[i].isNumber) {
i += 1
continue
}
if !(tempArr[j].isLetter || tempArr[j].isNumber) {
j -= 1
continue
}
if String(tempArr[i]).lowercased() == String(tempArr[j]).lowercased() {
i += 1
j -= 1
}else {
return false
}
}
return true
}
解题思路2: 反序后比较
将字符数字过滤出来以后, 反序后与原来进行对比, 我们使用系统的方法, 代码极其简单
示例代码2:
func isPalindrome(_ s: String) -> Bool {
let temp = s.filter { (c) -> Bool in
return c.isNumber || c.isLetter
}.lowercased()
return temp.reversed().elementsEqual(temp)
}