Skip to content

Commit 3304848

Browse files
Update the read for palindromes
1 parent fe93184 commit 3304848

File tree

1 file changed

+68
-33
lines changed

1 file changed

+68
-33
lines changed

Palindromes/README.markdown

Lines changed: 68 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -1,64 +1,99 @@
11
# Palindromes
22

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.
3+
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.
74

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

107
## Example
118

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.
9+
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`.
10+
`raceCar`
11+
`r a c e c a r`
12+
`r?a?c?e?c?a?r?`
13+
`RACEcar`
1414

1515
## Algorithm
1616

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.
17+
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.
2018

21-
In this implementation of a palindrome checker, recursion is used to check each substring of the
22-
original String.
19+
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.
2320

2421
## The code
2522

2623
Here is a recursive implementation of this in Swift:
2724

2825
```swift
29-
func palindromeCheck (text: String?) -> Bool {
30-
if let text = text {
31-
let mutableText = text.trimmingCharacters(in: NSCharacterSet.whitespaces()).lowercased()
32-
let length: Int = mutableText.characters.count
33-
34-
guard length >= 1 else {
35-
return false
36-
}
37-
38-
if length == 1 {
39-
return true
40-
} else if mutableText[mutableText.startIndex] == mutableText[mutableText.index(mutableText.endIndex, offsetBy: -1)] {
41-
let range = Range<String.Index>(mutableText.index(mutableText.startIndex, offsetBy: 1)..<mutableText.index(mutableText.endIndex, offsetBy: -1))
42-
return palindromeCheck(text: mutableText.substring(with: range))
43-
}
44-
}
45-
46-
return false
26+
func isPalindrome(_ str: String) -> Bool {
27+
let strippedString = str.replacingOccurrences(of: "\\W", with: "", options: .regularExpression, range: nil)
28+
let length = strippedString.characters.count
29+
30+
if length > 1 {
31+
return palindrome(strippedString.lowercased(), left: 0, right: length - 1)
32+
}
33+
return false
34+
}
35+
36+
private func palindrome(_ str: String, left: Int, right: Int) -> Bool {
37+
if left >= right {
38+
return true
39+
}
40+
41+
let lhs = str[str.index(str.startIndex, offsetBy: left)]
42+
let rhs = str[str.index(str.startIndex, offsetBy: right)]
43+
44+
if lhs != rhs {
45+
return false
4746
}
47+
48+
return palindrome(str, left: left + 1, right: right - 1)
49+
}
50+
```
51+
52+
This algorithm has a two-step process.
53+
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.
54+
55+
```swift
56+
let strippedString = str.replacingOccurrences(of: "\\W", with: "", options: .regularExpression, range: nil)
4857
```
4958

59+
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.
5060

51-
This code can be tested in a playground using the following:
61+
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.
62+
```swift
63+
if left >= right {
64+
return true
65+
}
66+
```
67+
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.
68+
```swift
69+
let lhs = str[str.index(str.startIndex, offsetBy: left)]
70+
let rhs = str[str.index(str.startIndex, offsetBy: right)]
5271

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

57-
Since the phrase "Race car" is a palindrome, this will return true.
81+
Step 1:
82+
` race?C ar -> raceCar -> racecar``
83+
84+
Step 2:
85+
| |
86+
racecar -> r == r
87+
| |
88+
racecar -> a == a
89+
| |
90+
racecar -> c == c
91+
|
92+
racecar -> left index == right index -> return true
5893

5994
## Additional Resources
6095

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

6398

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

0 commit comments

Comments
 (0)