|
1 | 1 | //: Playground - noun: a place where people can play
|
2 | 2 |
|
3 |
| -// last checked with Xcode 9.0b4 |
4 |
| -#if swift(>=4.0) |
5 |
| -print("Hello, Swift 4!") |
6 |
| -#endif |
7 |
| - |
8 | 3 | import Foundation
|
9 | 4 |
|
10 |
| -/** |
11 |
| - Validate that a string is a plaindrome |
12 |
| - - parameter str: The string to validate |
13 |
| - - returns: `true` if string is plaindrome, `false` if string is not |
14 |
| - */ |
15 |
| -func isPalindrome(_ str: String) -> Bool { |
16 |
| - let strippedString = str.replacingOccurrences(of: "\\W", with: "", options: .regularExpression, range: nil) |
17 |
| - let length = strippedString.characters.count |
18 |
| - |
19 |
| - if length > 1 { |
20 |
| - return palindrome(strippedString.lowercased(), left: 0, right: length - 1) |
21 |
| - } |
22 |
| - return false |
23 |
| -} |
24 |
| - |
25 |
| -/** |
26 |
| - Compares a strings left side character against right side character following |
27 |
| - - parameter str: The string to compare characters of |
28 |
| - - parameter left: Index of left side to compare, must be less than or equal to right |
29 |
| - - parameter right: Index of right side to compare, must be greater than or equal to left |
30 |
| - - returns: `true` if left side and right side have all been compared and they all match, `false` if a left and right aren't equal |
31 |
| - */ |
32 |
| -private func palindrome(_ str: String, left: Int, right: Int) -> Bool { |
33 |
| - if left >= right { |
34 |
| - return true |
35 |
| - } |
36 |
| - |
37 |
| - let lhs = str[str.index(str.startIndex, offsetBy: left)] |
38 |
| - let rhs = str[str.index(str.startIndex, offsetBy: right)] |
39 |
| - |
40 |
| - if lhs != rhs { |
41 |
| - return false |
42 |
| - } |
43 |
| - |
44 |
| - return palindrome(str, left: left + 1, right: right - 1) |
45 |
| -} |
46 |
| - |
47 | 5 | //true
|
48 | 6 | isPalindrome("A man, a plan, a canal, Panama!")
|
49 | 7 | isPalindrome("abbcbba")
|
|
0 commit comments