/*
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")
125. Valid Palindrome
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 1,输入Given a string, determine if it is a palindrome, cons...