forked from kodecocodes/swift-algorithm-club
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathContents.swift
66 lines (56 loc) · 1.9 KB
/
Contents.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
//: Playground - noun: a place where people can play
// last checked with Xcode 9.0b4
#if swift(>=4.0)
print("Hello, Swift 4!")
#endif
import Foundation
/**
Validate that a string is a plaindrome
- parameter str: The string to validate
- returns: `true` if string is plaindrome, `false` if string is not
*/
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
}
/**
Compares a strings left side character against right side character following
- parameter str: The string to compare characters of
- parameter left: Index of left side to compare, must be less than or equal to right
- parameter right: Index of right side to compare, must be greater than or equal to left
- 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
*/
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)
}
//true
isPalindrome("A man, a plan, a canal, Panama!")
isPalindrome("abbcbba")
isPalindrome("racecar")
isPalindrome("Madam, I'm Adam")
isPalindrome("Madam in Eden, I'm Adam")
isPalindrome("Never odd or even")
isPalindrome("5885")
isPalindrome("5 8 8 5")
isPalindrome("58 85")
isPalindrome("৯৯")
isPalindrome("In girum imus nocte et consumimur igni")
// false
isPalindrome("\\\\")
isPalindrome("desserts")
isPalindrome("😀😀")
isPalindrome("")
isPalindrome("a")
isPalindrome("power")