Skip to content

Commit

Permalink
Update the read for palindromes
Browse files Browse the repository at this point in the history
  • Loading branch information
lostatseajoshua committed Dec 22, 2016
1 parent fe93184 commit 3304848
Showing 1 changed file with 68 additions and 33 deletions.
101 changes: 68 additions & 33 deletions Palindromes/README.markdown
Original file line number Diff line number Diff line change
@@ -1,64 +1,99 @@
# Palindromes

A palindrome is a word or phrase that is spelled the exact same when read forwards or backwards.
For this example puzzle, palindromes will not take case into account, meaning that uppercase and
lowercase text will be treated the same. In addition, spaces will not be considered, allowing
for multi-word phrases to constitute palindromes too.
A palindrome is a word or phrase that is spelled the exact same when reading it forwards or backward. Palindromes are allowed to be lowercase or uppercase, contain spaces, punctuation, and word dividers.

Algorithms that check for palindromes are a common programming interview question.

## Example

The word "radar" is spelled the exact same both forwards and backwards, and as a result is a palindrome.
The phrase "race car" is another common palindrome that is spelled the same forwards and backwards.
The word racecar is a valid palindrome, as it is a word spelled the same when backgrounds and forwards. The examples below shows valid cases of the palindrome `racecar`.
`raceCar`
`r a c e c a r`
`r?a?c?e?c?a?r?`
`RACEcar`

## Algorithm

To check for palindromes, the first and last characters of a String must be compared for equality.
When the first and last characters are the same, they are removed from the String, resulting in a
substring starting with the second character and ending at the second to last character.
To check for palindromes, a strings character are compared starting from the beginning and end and moving inward moving to toward the middle of the string and keep the same distance apart in the comparison index.

In this implementation of a palindrome checker, recursion is used to check each substring of the
original String.
In this implementation of a palindrome algorithm, recursion is used to check each of the characters on the left-hand side and right-hand side moving inward.

## The code

Here is a recursive implementation of this in Swift:

```swift
func palindromeCheck (text: String?) -> Bool {
if let text = text {
let mutableText = text.trimmingCharacters(in: NSCharacterSet.whitespaces()).lowercased()
let length: Int = mutableText.characters.count

guard length >= 1 else {
return false
}

if length == 1 {
return true
} else if mutableText[mutableText.startIndex] == mutableText[mutableText.index(mutableText.endIndex, offsetBy: -1)] {
let range = Range<String.Index>(mutableText.index(mutableText.startIndex, offsetBy: 1)..<mutableText.index(mutableText.endIndex, offsetBy: -1))
return palindromeCheck(text: mutableText.substring(with: range))
}
}

return false
func isPalindrome(_ str: String) -> Bool {
let strippedString = str.replacingOccurrences(of: "\\W", with: "", options: .regularExpression, range: nil)
let length = strippedString.characters.count

if length > 1 {
return palindrome(strippedString.lowercased(), left: 0, right: length - 1)
}
return false
}

private func palindrome(_ str: String, left: Int, right: Int) -> Bool {
if left >= right {
return true
}

let lhs = str[str.index(str.startIndex, offsetBy: left)]
let rhs = str[str.index(str.startIndex, offsetBy: right)]

if lhs != rhs {
return false
}

return palindrome(str, left: left + 1, right: right - 1)
}
```

This algorithm has a two-step process.
1. The first step is to pass the string to validate as a palindrome into the `isPalindrome` method. This method first removes occurrences of non-word pattern matches `\W` [Regex reference](http://regexr.com). It is written with two \\ to escape the \ in the String literal.

```swift
let strippedString = str.replacingOccurrences(of: "\\W", with: "", options: .regularExpression, range: nil)
```

The length of the string is then checked to make sure that the string after being stripped of non-word characters is still in a valid length. It is then passed into the next step after being lowercased.

This code can be tested in a playground using the following:
2. The second step is to pass the string in a recursive method. This method takes a string, a left index, and a right index. The method checks the characters of the string using the indexes to compare each character on both sides. The method checks if the left is greater or equal to the right if so the entire string has been run through without returning false so the string is equal on both sides thus returning true.
```swift
if left >= right {
return true
}
```
If the check doesn't pass it continues to get the characters at the specified indexes and compare each. If they are not the same the method returns false and exits.
```swift
let lhs = str[str.index(str.startIndex, offsetBy: left)]
let rhs = str[str.index(str.startIndex, offsetBy: right)]

if lhs != rhs {
return false
}
```
If they are the same the method calls itself again and updates the indexes accordingly to continue to check the rest of the string.
```swift
palindromeCheck(text: "Race car")
return palindrome(str, left: left + 1, right: right - 1)
```

Since the phrase "Race car" is a palindrome, this will return true.
Step 1:
` race?C ar -> raceCar -> racecar``

Step 2:
| |
racecar -> r == r
| |
racecar -> a == a
| |
racecar -> c == c
|
racecar -> left index == right index -> return true

## Additional Resources

[Palindrome Wikipedia](https://en.wikipedia.org/wiki/Palindrome)


*Written by [Stephen Rutstein](https://github.com/srutstein21)*
*Written by [Joshua Alvarado](https://github.com/https://github.com/lostatseajoshua)*

0 comments on commit 3304848

Please sign in to comment.