Skip to content

Instantly share code, notes, and snippets.

@AustinBCole
Created November 13, 2018 16:44
Show Gist options
  • Save AustinBCole/8ceb5ecc8fbce457462dc244aff573f2 to your computer and use it in GitHub Desktop.
Save AustinBCole/8ceb5ecc8fbce457462dc244aff573f2 to your computer and use it in GitHub Desktop.
Daily Challenge Nov. 13th Austin Cole
Assumptions:
I assume that neither punctuation, numbers nor spaces will not count toward whether or not a word is a palindrome, so I will want to
exclude those in my function. I also want to guard against empty strings.
Test Cases:
"Sally"
"race car"
"race car!?"
""
Approach:
I will filter out non-letter characters and empty strings. I will write a for loop that places each character of the string
into an array. If the array already contains the character then the double character will be put into another array using. I will
check for this using .contains. I will then use an if statement to see if the first array has the same number of characters
as the second array, plus one more. If true then they are a palindrome. If not then they are not a palindrome.
Code:
func canBePalindrome(_ word: String?) -> Bool {
//I create two arrays that I will use to store the first instance of a character and then the
//second instance of that same character
var charArray : [Character] = []
var doubleCharArray: [Character] = []
if let newWord = word {
for char in newWord {
//I am only filtering out spaces here because I do not remember the syntax required to
//filter out all non-letter characters
if char != " " {
if charArray.contains(char) == false {
charArray.append(char)
} else {
doubleCharArray.append(char)
}
}
}
//Here I am checking to see if the doubleCharArray has only one less character than the
//charArray.
if doubleCharArray.count == charArray.count - 1 {
return true
} else {
return false
}
} else {
return false
}
}
canBePalindrome("Sally")
canBePalindrome("racecar")
canBePalindrome("dad")
canBePalindrome("race car")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment