forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0131-palindrome-partitioning.kt
More file actions
36 lines (32 loc) · 904 Bytes
/
0131-palindrome-partitioning.kt
File metadata and controls
36 lines (32 loc) · 904 Bytes
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
class Solution {
fun partition(s: String): List<List<String>> {
val res = mutableListOf<MutableList<String>>()
val part = mutableListOf<String>()
fun isPalindrome(_l: Int, _r: Int): Boolean {
var l = _l
var r = _r
while (l < r) {
if (s[l] != s[r])
return false
l++
r--
}
return true
}
fun dfs(i: Int) {
if (i >= s.length) {
res.add(part.toMutableList())
return
}
for (j in i until s.length) {
if (isPalindrome(i, j)) {
part.add(s.substring(i, j + 1))
dfs(j + 1)
part.removeAt(part.lastIndex)
}
}
}
dfs(0)
return res
}
}