Skip to content

Commit d516211

Browse files
author
Aleksandr
committed
Swift: 131. Palindrome Partitioning
1 parent 336e02e commit d516211

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

Diff for: swift/0131-palindrome-partitioning.swift

+34
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
class Solution {
2+
func isPalindrom(_ characters: [Character]) -> Bool {
3+
guard !characters.isEmpty else { return false }
4+
var i = 0
5+
var j = characters.count - 1
6+
while i < j {
7+
guard characters[i] == characters[j] else { return false }
8+
i += 1
9+
j -= 1
10+
}
11+
return true
12+
}
13+
func partition(_ s: String) -> [[String]] {
14+
var substrings: [String] = []
15+
var result: [[String]] = []
16+
let characters = s.map { $0 }
17+
18+
func dfs(_ start: Int) {
19+
guard start < s.count else {
20+
result.append(substrings)
21+
return
22+
}
23+
for end in start..<characters.count {
24+
let substring = Array(characters[start...end])
25+
guard isPalindrom(substring) else { continue }
26+
substrings.append(substring.map { String($0) }.joined())
27+
dfs(end + 1)
28+
substrings.removeLast()
29+
}
30+
}
31+
dfs(0)
32+
return result
33+
}
34+
}

0 commit comments

Comments
 (0)