-
Notifications
You must be signed in to change notification settings - Fork 886
/
PalindromePartitioning.swift
53 lines (43 loc) · 1.31 KB
/
PalindromePartitioning.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
/**
* Question Link: https://leetcode.com/problems/palindrome-partitioning/
* Primary idea: Classic Depth-first Search, use index to track substring,
* and move forward to deeper level only if the substring is a palindrome
*
* Time Complexity: O(n^n), Space Complexity: O(n)
*
*/
class PalindromePartitioning {
func partition(_ s: String) -> [[String]] {
var paths = [[String]](), path = [String]()
dfs(&paths, &path, Array(s), 0)
return paths
}
fileprivate func dfs(_ paths: inout [[String]], _ path: inout [String], _ s: [Character], _ index: Int) {
if index == s.count {
paths.append(Array(path))
return
}
for i in index..<s.count {
let current = String(s[index...i])
if current.isPalindrome {
path.append(current)
dfs(&paths, &path, s, i + 1)
path.removeLast()
}
}
}
}
extension String {
var isPalindrome: Bool {
let chars = Array(self)
var i = 0, j = count - 1
while i <= j {
if chars[i] != chars[j] {
return false
}
i += 1
j -= 1
}
return true
}
}