Created
August 4, 2020 15:52
-
-
Save tmm/d1ca31d2e789572ff217e18f2c610eca to your computer and use it in GitHub Desktop.
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 UIKit | |
extension String { | |
func isAlphanumeric() -> Bool { | |
return self.rangeOfCharacter(from: CharacterSet.alphanumerics.inverted) == nil && self != "" | |
} | |
func isAlphanumeric(ignoreDiacritics: Bool = false) -> Bool { | |
if ignoreDiacritics { return self.range(of: "[^a-zA-Z0-9]", options: .regularExpression) == nil && self != "" } | |
else { return self.isAlphanumeric() } | |
} | |
} | |
func isPalindrome(string: String) -> Bool { | |
var newString = string | |
for char in string { | |
if !"\(char)".isAlphanumeric() { continue } | |
while newString.count > 0 { | |
guard let lastChar = newString.last else { break } | |
newString = String(newString.dropLast()) | |
if char.lowercased() == lastChar.lowercased() { break } | |
if "\(lastChar)".isAlphanumeric() { return false } | |
} | |
} | |
return true | |
} | |
isPalindrome(string: "level") == true ? print("passed") : print("failed") | |
isPalindrome(string: "algorithm") == false ? print("passed") : print("failed") | |
isPalindrome(string: "A man, a plan, a canal: Panama.") == true ? print("passed") : print("failed") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment