[Swift]LeetCode125. 验证回文串 | Valid Palindrome
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:https://www.cnblogs.com/strengthen/p/9709977.html
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
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:
输入: "A man, a plan, a canal: Panama" 输出: true
示例 2:
输入: "race a car" 输出: false
28ms
1 class Solution { 2 func isPalindrome(_ s: String) -> Bool { 3 4 let lowerS = s.lowercased() 5 var ints = [UInt32]() 6 for scalars in lowerS.unicodeScalars { 7 ints.append(scalars.value) 8 } 9 var i = 0 10 var j = ints.count - 1 11 12 while i < j { 13 if !isCharOrNumber(ints[i]) { 14 i += 1 15 }else if !isCharOrNumber(ints[j]) { 16 j -= 1 17 }else if ints[i] != ints[j] { 18 return false 19 }else { 20 i += 1 21 j -= 1 22 } 23 } 24 return true 25 26 } 27 28 func isCharOrNumber(_ character: UInt32) -> Bool { 29 if character >= 97 && character <= 122 { 30 return true 31 } 32 33 if character >= 48 && character <= 57 { 34 return true 35 } 36 return false 37 } 38 }
32ms
1 class Solution { 2 func isPalindrome(_ s: String) -> Bool { 3 if s.count == 0 { 4 return true 5 } 6 7 var chas = s.cString(using:.ascii)! 8 9 var left = 0 10 var right = s.count - 1 11 12 var loop = true 13 14 while loop { 15 if left > right { 16 loop = false 17 continue 18 } 19 20 let leftChar = chas[left] 21 22 if !checkIsNormalChar(leftChar) { 23 left = left + 1 24 continue 25 } 26 27 let rightChar = chas[right] 28 29 if !checkIsNormalChar(rightChar) { 30 right = right - 1 31 continue 32 } 33 34 if isEqual(leftChar,rightChar) { 35 left = left + 1 36 right = right - 1 37 } else { 38 return false 39 } 40 41 } 42 return true 43 } 44 45 func isEqual(_ c:CChar, _ other:CChar) -> Bool { 46 if c == other { 47 return true 48 } 49 var newC = c 50 if c >= 97 { 51 newC = c - 32; 52 } 53 54 var newOther = other 55 56 if other >= 97 { 57 newOther = other - 32 58 } 59 60 return newC == newOther 61 } 62 63 func checkIsNormalChar(_ c: CChar) -> Bool { 64 if c < 48 { 65 return false 66 } 67 68 if c > 122 { 69 return false 70 } 71 72 if c > 57 && c < 65 { 73 return false 74 } 75 76 if c > 90 && c < 97 { 77 return false 78 } 79 80 return true 81 } 82 }