Skip to content

Commit 607819e

Browse files
committed
Add a solution to Word Break
1 parent bb20cd5 commit 607819e

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

DP/WordBreak.swift

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
/**
2+
* Question Link: https://leetcode.com/problems/word-break/
3+
* Primary idea: DP. dp[i] = dp[j] && dict.contains(s[j..<i]). Break the operation if current index is already true.
4+
* Time Complexity: O(n^3), Space Complexity: O(n)
5+
*/
6+
7+
class WordBreak {
8+
func wordBreak(_ s: String, _ wordDict: [String]) -> Bool {
9+
let dict = Set(wordDict), s = Array(s)
10+
var dp = Array(repeating: false, count: s.count + 1)
11+
dp[0] = true
12+
13+
for i in 1...s.count {
14+
for j in 0..<i {
15+
let currentStr = String(s[j..<i])
16+
17+
if dp[j] && wordDict.contains(currentStr) {
18+
dp[i] = true
19+
break
20+
}
21+
}
22+
}
23+
24+
return dp[s.count]
25+
}
26+
}

0 commit comments

Comments
 (0)