Skip to content

Instantly share code, notes, and snippets.

@macbellingrath
Last active October 17, 2018 14:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save macbellingrath/54e8bdfafbb19275b0658bc4c021ac76 to your computer and use it in GitHub Desktop.
Save macbellingrath/54e8bdfafbb19275b0658bc4c021ac76 to your computer and use it in GitHub Desktop.
10/16/18 - Johnny from FB
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