125. Valid Palindrome
2017-01-26 本文已影响11人
小万叔叔
/*
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
For example,
"A man, a plan, a canal: Panama" is a palindrome.
"race a car" is not a palindrome.
Note:
Have you consider that the string might be empty? This is a good question to ask during an interview.
For the purpose of this problem, we define empty string as valid palindrome.
*/
/*
1. 忽略大小写
2. 只关注字母,过滤所有其他字符
*/
func isPalindrome(_ s: String) -> Bool {
//空字符串和单个字符都是回文
guard s.lengthOfBytes(using: .ascii) > 1 else {
return true
}
let aValue = Int8(UnicodeScalar("A")!.value)
let zValue = Int8(UnicodeScalar("Z")!.value)
let zeroValue = Int8(UnicodeScalar("0")!.value)
let nineValue = Int8(UnicodeScalar("9")!.value)
//忽略大小写匹配
func isMatchLetter(_ l: CChar, _ r:CChar) -> Bool {
if l == r {
return true
}
return false
}
//是否匹配字母或数字
func isLetterOrNumber(_ c: CChar) -> Bool {
if ((c >= aValue && c <= zValue) || (c >= zeroValue && c <= nineValue)) {
return true
}
return false
}
let upperS = s.uppercased()
let cCharArray = upperS.cString(using: .ascii)!
let length = cCharArray.count
var left = 0
var right = length - 1
while left < right {
if isLetterOrNumber(cCharArray[left]) {
if isLetterOrNumber(cCharArray[right]) {
if !isMatchLetter(cCharArray[left], cCharArray[right]) {
return false
}
else {
left += 1
right -= 1
}
}
else {
right -= 1
}
}
else {
left += 1
}
}
return true
}
isPalindrome("A man, a plan, a canal: Panama")
isPalindrome("race a car")