Every kid is dazzled at palindromes. It’s the same word or sentence backwards! What black magic is this? With my name being Adam, I couldn’t escape “Madam Im Adam.”
Who knew that decades later this would be a popular interview question for programmers?
There is a super duper easy way to solve this, with a pretty brief function.
//Needed to get the lowercased function
import Foundation
//Input a string and output true or false
func checkIfPalindrome(phrase: String) -> Bool {
//Remove spaces and make everything lowercase (palindromes are case insensitive)
var cleanPhrase = phrase.replacingOccurrences(of: " ", with: "").lowercased()
//Compare the cleanPhrase to the reverse of it (which must be converted to String)
return cleanPhrase == String(cleanPhrase.reversed())
}
print(checkIfPalindrome(phrase: "Madam Im Adam"))
//True
What about other symbols, like the apostrophe in I’m? This would break it, so if I wanted to be thorough I’d have to remove all non-letter characters.
But when you get asked about palindromes, usually using built in functions leads to… “Oh that’s nice, now try it a different way.”
import Foundation
func checkIfPalindrome(phrase: String) -> Bool {
var cleanPhrase = phrase.replacingOccurrences(of: " ", with: "").lowercased()
//Set up a blank array of characters
var reversedPhraseArr = [Character]()
//Iterate through each character of the phrase
for c in cleanPhrase {
//For the first character, just add it into the blank character array.
if reversedPhraseArr.count == 0 {
reversedPhraseArr.append(c)
//For every new character, add it in the first position of the array
} else {
reversedPhraseArr.insert(c, at: 0)
}
}
//Turn the character array back to a string
let reversedPhrase = String(reversedPhraseArr)
//Finally do a comparison
return cleanPhrase == reversedPhrase
}
print(checkIfPalindrome(phrase: "Madam Im Adam"))
//True
The first is pretty easy to remember. The second one has a bunch of more steps. That’s why it is always a one-two punch.
Then again, I’m sure there is a third punch on using a better Big O notation and increasing the speed efficiency of this function. That will be another day…