Skip to content

Commit 3dd0674

Browse files
Update palindrome swift file contents
1 parent e61e743 commit 3dd0674

File tree

1 file changed

+22
-13
lines changed

1 file changed

+22
-13
lines changed

Palindromes/Palindromes.swift

Lines changed: 22 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,26 @@
1-
import Cocoa
1+
import Foundation
22

3-
public func palindromeCheck(text: String?) -> Bool {
4-
if let text = text {
5-
let mutableText = text.trimmingCharacters(in: NSCharacterSet.whitespaces).lowercased()
6-
let length: Int = mutableText.characters.count
3+
func isPalindrome(_ str: String) -> Bool {
4+
let strippedString = str.replacingOccurrences(of: "\\W", with: "", options: .regularExpression, range: nil)
5+
let length = strippedString.characters.count
76

8-
if length == 1 || length == 0 {
9-
return true
10-
} else if mutableText[mutableText.startIndex] == mutableText[mutableText.index(mutableText.endIndex, offsetBy: -1)] {
11-
let range = Range<String.Index>(mutableText.index(mutableText.startIndex, offsetBy: 1)..<mutableText.index(mutableText.endIndex, offsetBy: -1))
12-
return palindromeCheck(text: mutableText.substring(with: range))
7+
if length > 1 {
8+
return palindrome(strippedString.lowercased(), left: 0, right: length - 1)
139
}
14-
}
15-
16-
return false
10+
return false
11+
}
12+
13+
private func palindrome(_ str: String, left: Int, right: Int) -> Bool {
14+
if left >= right {
15+
return true
16+
}
17+
18+
let lhs = str[str.index(str.startIndex, offsetBy: left)]
19+
let rhs = str[str.index(str.startIndex, offsetBy: right)]
20+
21+
if lhs != rhs {
22+
return false
23+
}
24+
25+
return palindrome(str, left: left + 1, right: right - 1)
1726
}

0 commit comments

Comments
 (0)