[Geeks for Geeks] Word Break

Word Break

Given a string A and a dictionary of n words B, find out if A can be segmented into a space-separated sequence of dictionary words.

Note: From the dictionary B each word can be taken any number of times and in any order.

  • Time : O(|s|^2)
  • Space : O(n + |s|)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public:
int wordBreak(string A, vector<string> &B) {
unordered_set<string> mp(begin(B), end(B));
int n = A.size();
vector<bool> dp(n + 1, false);
for(int i = 1; i <= n; i++) {
if(!dp[i]) dp[i] = mp.count(A.substr(0,i));
if(!dp[i]) continue;
for(int j = i + 1; j <= n; j++) {
if(mp.count(A.substr(i, j - i)))
dp[j] = true;
}
}
return dp.back();
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/17/PS/GeeksforGeeks/word-break/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.