Skip to content

Instantly share code, notes, and snippets.

@chadparker
Last active February 11, 2020 04:21
Show Gist options
  • Save chadparker/202e06bbdc92ef2d3d58751166feeef3 to your computer and use it in GitHub Desktop.
Save chadparker/202e06bbdc92ef2d3d58751166feeef3 to your computer and use it in GitHub Desktop.
Palindrome checker
import Foundation
// Requirements:
// ignore case, whitespace, and punctuation
// check from each end of the string
// deal with even or odd amount of characters
func canBePalindrome(_ string: String) -> Bool {
var preparedString = string.lowercased()
// remove spaces, common punctuation
preparedString = preparedString.filter { $0 != " " }
preparedString = preparedString.filter { $0 != "." }
preparedString = preparedString.filter { $0 != "," }
print(preparedString)
return preparedString == String(preparedString.reversed())
}
// Test Cases
canBePalindrome("tacocat") // should return true
canBePalindrome("daily") // should return false
canBePalindrome("a") // should return true
canBePalindrome("aa") // should return true
canBePalindrome("hannah") // should return true
canBePalindrome("abc") // should return false
canBePalindrome("Racecar")
canBePalindrome("A man, a plan, a can ... na canal panama.")
// I was starting with something like this, until I realized I could just reverse the whole string:
//let stringBeginning = ""
//let stringEnd = ""
//if preparedString.count % 2 == 0 {
// //even
// for letter in
//} else {
// //odd
//}
// trying my own string reversing function:
func reversedString(_ string: String) -> String {
var reversedString = ""
for character in string {
reversedString.insert(character, at: reversedString.startIndex)
}
return reversedString
}
reversedString("reversed string")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment