File tree 1 file changed +35
-1
lines changed
cpp/neetcode_150/13_1-d_dynamic_programming
1 file changed +35
-1
lines changed Original file line number Diff line number Diff line change 7
7
Time: O(n^3)
8
8
Space: O(n)
9
9
*/
10
-
10
+ /*
11
11
class Solution {
12
12
public:
13
13
bool wordBreak(string s, vector<string>& wordDict) {
@@ -35,3 +35,37 @@ class Solution {
35
35
return dp[n];
36
36
}
37
37
};
38
+ */
39
+
40
+ /*
41
+ Given a string & dictionary, return true if:
42
+ Can segment string into 1 or more dictionary words
43
+
44
+ Bottom-up DP: for each position in the string, loop over
45
+ the words in the dictionary. If the word matches the substring
46
+ starting at the current position, assign to the DP array in the
47
+ same position the same value of the DP array at position + matched_word
48
+ length.
49
+
50
+ Time: O(n^2 * m)
51
+ Space: O(n)
52
+ */
53
+ class Solution {
54
+ public:
55
+ bool wordBreak (string s, vector<string>& wordDict) {
56
+ int strSize = s.size ();
57
+ vector<bool > dp (strSize + 1 );
58
+ dp[strSize] = true ;
59
+
60
+ for (int i = strSize - 1 ; i >= 0 ; --i){
61
+ for (string& w : wordDict){
62
+ if (i + w.size () <= strSize && s.substr (i, w.size ()) == w)
63
+ dp[i] = dp[i + w.size ()];
64
+ if (dp[i])
65
+ break ;
66
+ }
67
+ }
68
+
69
+ return dp[0 ];
70
+ }
71
+ };
You can’t perform that action at this time.
0 commit comments