Skip to content

Commit 21a78d3

Browse files
authored
Update word_break.cpp
1 parent ece76f2 commit 21a78d3

File tree

1 file changed

+35
-1
lines changed

1 file changed

+35
-1
lines changed

Diff for: cpp/neetcode_150/13_1-d_dynamic_programming/word_break.cpp

+35-1
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
Time: O(n^3)
88
Space: O(n)
99
*/
10-
10+
/*
1111
class Solution {
1212
public:
1313
bool wordBreak(string s, vector<string>& wordDict) {
@@ -35,3 +35,37 @@ class Solution {
3535
return dp[n];
3636
}
3737
};
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+
};

0 commit comments

Comments
 (0)