We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent bb20cd5 commit 607819eCopy full SHA for 607819e
DP/WordBreak.swift
@@ -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