Skip to content

Commit 8350203

Browse files
authored
Create 139. Word Break.cpp
1 parent 2b28530 commit 8350203

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

139. Word Break.cpp

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
class Solution {
2+
public:
3+
unordered_map<string, int> map;
4+
int dp[305][305];
5+
bool solve(string &s, int n, int start){
6+
if(start==n) return true;
7+
if(dp[start][n]!=-1) return dp[start][n];
8+
for(int i=start; i<n; ++i){
9+
string str = s.substr(start,i-start+1);
10+
if(map.find(str)!=map.end()){
11+
if(solve(s,n,i+1)) return dp[start][n] = true;
12+
}
13+
}
14+
return dp[start][n] = false;
15+
}
16+
bool wordBreak(string &s, vector<string>& wordDict) {
17+
memset(dp,-1,sizeof(dp));
18+
for(auto &word : wordDict) map[word]++;
19+
int n=s.size();
20+
return solve(s,n,0);
21+
}
22+
};

0 commit comments

Comments
 (0)