Skip to content

Commit cb8ba7b

Browse files
committed
Add a solution to Word Break II
1 parent 28ec17b commit cb8ba7b

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

DFS/WordBreakII.swift

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/**
2+
* Question Link: https://leetcode.com/problems/word-break-ii/
3+
* Primary idea: DFS. Termination case is index hits the end of the string
4+
*
5+
* Time Complexity: O(n), Space Complexity: O(n)
6+
*
7+
*/
8+
9+
class WordBreakII {
10+
func wordBreak(_ s: String, _ wordDict: [String]) -> [String] {
11+
var res = [String](), path = [String]()
12+
13+
dfs(&res, &path, Array(s), Set(wordDict), 0)
14+
15+
return res
16+
}
17+
18+
private func dfs(_ res: inout [String], _ path: inout [String], _ s: [Character], _ dict: Set<String>, _ idx: Int) {
19+
if idx >= s.count {
20+
res.append(path.joined(separator: " "))
21+
return
22+
}
23+
24+
for i in idx..<s.count {
25+
let currentWord = String(s[idx...i])
26+
27+
guard dict.contains(currentWord) else {
28+
continue
29+
}
30+
31+
path.append(currentWord)
32+
dfs(&res, &path, s, dict, i + 1)
33+
path.removeLast()
34+
}
35+
}
36+
}

0 commit comments

Comments
 (0)