|
| 1 | +# Palindromes |
| 2 | + |
| 3 | +A palindrome is a word or phrase that is spelled the exact same when read forwards or backwards. |
| 4 | +For this example puzzle, palindromes will not take case into account, meaning that uppercase and |
| 5 | +lowercase text will be treated the same. In addition, spaces will not be considered, allowing |
| 6 | +for multi-word phrases to constitute palindromes too. |
| 7 | + |
| 8 | +Algorithms that check for palindromes are a common programming interview question. |
| 9 | + |
| 10 | +## Example |
| 11 | + |
| 12 | +The word "radar" is spelled the exact same both forwards and backwards, and as a result is a palindrome. |
| 13 | +The phrase "race car" is another common palindrome that is spelled the same forwards and backwards. |
| 14 | + |
| 15 | +## Algorithm |
| 16 | + |
| 17 | +To check for palindromes, the first and last characters of a String must be compared for equality. |
| 18 | +When the first and last characters are the same, they are removed from the String, resulting in a |
| 19 | +substring starting with the second character and ending at the second to last character. |
| 20 | + |
| 21 | +In this implementation of a palindrome checker, recursion is used to check each substring of the |
| 22 | +original String. |
| 23 | + |
| 24 | +## The code |
| 25 | + |
| 26 | +Here is a recursive implementation of this in Swift: |
| 27 | + |
| 28 | +``swift |
| 29 | +func palindromeCheck (text: String?) -> Bool { |
| 30 | + if let text = text { |
| 31 | + let mutableText = text.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()).lowercaseString |
| 32 | + let length: Int = mutableText.characters.count |
| 33 | + |
| 34 | + if length < 1 { |
| 35 | + return false |
| 36 | + } |
| 37 | + |
| 38 | + if length == 1 { |
| 39 | + return true |
| 40 | + } else if mutableText[mutableText.startIndex] == mutableText[mutableText.endIndex.predecessor()] { |
| 41 | + let range = Range<String.Index>(mutableText.startIndex.successor()..<mutableText.endIndex.predecessor()) |
| 42 | + return palindromeCheck(mutableText.substringWithRange(range)) |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + return false |
| 47 | +} |
| 48 | +`` |
| 49 | + |
| 50 | + |
| 51 | +This code can be tested in a playground using the following: |
| 52 | + |
| 53 | +``swift |
| 54 | +palindromeCheck("Race car") |
| 55 | +`` |
| 56 | + |
| 57 | +Since the phrase "Race car" is a palindrome, this will return true. |
| 58 | + |
| 59 | +## Additional Resources |
| 60 | + |
| 61 | +[Palindrome Wikipedia](https://en.wikipedia.org/wiki/Palindrome) |
| 62 | + |
| 63 | + |
| 64 | +*Written by [Stephen Rutstein](https://github.com/srutstein21)* |
0 commit comments