forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0131-palindrome-partitioning.swift
34 lines (33 loc) · 1.03 KB
/
0131-palindrome-partitioning.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
class Solution {
func isPalindrom(_ characters: [Character]) -> Bool {
guard !characters.isEmpty else { return false }
var i = 0
var j = characters.count - 1
while i < j {
guard characters[i] == characters[j] else { return false }
i += 1
j -= 1
}
return true
}
func partition(_ s: String) -> [[String]] {
var substrings: [String] = []
var result: [[String]] = []
let characters = s.map { $0 }
func dfs(_ start: Int) {
guard start < s.count else {
result.append(substrings)
return
}
for end in start..<characters.count {
let substring = Array(characters[start...end])
guard isPalindrom(substring) else { continue }
substrings.append(substring.map { String($0) }.joined())
dfs(end + 1)
substrings.removeLast()
}
}
dfs(0)
return result
}
}