Last active
October 17, 2018 14:30
-
-
Save macbellingrath/54e8bdfafbb19275b0658bc4c021ac76 to your computer and use it in GitHub Desktop.
10/16/18 - Johnny from FB
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
extension String { | |
/// Returns true if a string is a valid palindrome. | |
var isPalindrome: Bool { | |
let scalars = utf16 | |
if scalars.count < 2 { return true } | |
var i = scalars.startIndex | |
var j = scalars.index(before: scalars.endIndex) | |
let charSet = CharacterSet.alphanumerics | |
while i < j { | |
guard let left = Unicode.Scalar(scalars[i]), charSet.contains(left) else { | |
scalars.formIndex(after: &i) // i++ Unicode.Scalar.UTF16View is RandomAccessCollection, therefore the runtime is O(1) | |
continue | |
} | |
guard let right = Unicode.Scalar(scalars[j]), charSet.contains(right) else { | |
scalars.formIndex(before: &j) // j-- ^ | |
continue | |
} | |
guard String(left).lowercased() == String(right).lowercased() else { | |
return false | |
} | |
scalars.formIndex(after: &i) | |
scalars.formIndex(before: &j) | |
} | |
return true | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment