Skip to content

Commit

Permalink
Merge pull request neetcode-gh#1530 from elcabalero/patch-8
Browse files Browse the repository at this point in the history
Modified word_break.cpp as in the video
  • Loading branch information
neetcode-gh committed Dec 9, 2022
2 parents a2e4e75 + 21a78d3 commit 456f323
Showing 1 changed file with 35 additions and 1 deletion.
36 changes: 35 additions & 1 deletion cpp/neetcode_150/13_1-d_dynamic_programming/word_break.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
Time: O(n^3)
Space: O(n)
*/

/*
class Solution {
public:
bool wordBreak(string s, vector<string>& wordDict) {
Expand Down Expand Up @@ -35,3 +35,37 @@ class Solution {
return dp[n];
}
};
*/

/*
Given a string & dictionary, return true if:
Can segment string into 1 or more dictionary words
Bottom-up DP: for each position in the string, loop over
the words in the dictionary. If the word matches the substring
starting at the current position, assign to the DP array in the
same position the same value of the DP array at position + matched_word
length.
Time: O(n^2 * m)
Space: O(n)
*/
class Solution {
public:
bool wordBreak(string s, vector<string>& wordDict) {
int strSize = s.size();
vector<bool> dp(strSize + 1);
dp[strSize] = true;

for (int i = strSize - 1; i >= 0; --i){
for (string& w : wordDict){
if (i + w.size() <= strSize && s.substr(i, w.size()) == w)
dp[i] = dp[i + w.size()];
if (dp[i])
break;
}
}

return dp[0];
}
};

0 comments on commit 456f323

Please sign in to comment.