forked from TheAlgorithms/Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpalindrome_recursion.swift
44 lines (40 loc) · 1.43 KB
/
palindrome_recursion.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
// A palindrome is a string that reads the same forwards and backwards.
//
// Examples: "level", "radar", "madam", "A man, a plan, a canal: Panama".
extension String {
/// Recursively comparing characters from the beginning and end of the string. Only include letters and numbers.
/// - Complexity: O(n), without allocating new space.
func isPalindrome() -> Bool {
isPalindromeRecursion(
leftIndex: startIndex,
rightIndex: index(before: endIndex)
)
}
private func isPalindromeRecursion(
leftIndex: String.Index,
rightIndex: String.Index
) -> Bool {
guard leftIndex < rightIndex else {
return true
}
guard self[leftIndex].isLetter || self[leftIndex].isNumber else {
return isPalindromeRecursion(
leftIndex: index(after: leftIndex),
rightIndex: rightIndex
)
}
guard self[rightIndex].isLetter || self[rightIndex].isNumber else {
return isPalindromeRecursion(
leftIndex: leftIndex,
rightIndex: index(before: rightIndex)
)
}
guard self[leftIndex].lowercased() == self[rightIndex].lowercased() else {
return false
}
return isPalindromeRecursion(
leftIndex: index(after: leftIndex),
rightIndex: index(before: rightIndex)
)
}
}