-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWordBreak.cpp
More file actions
55 lines (52 loc) · 1.69 KB
/
Copy pathWordBreak.cpp
File metadata and controls
55 lines (52 loc) · 1.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include <string>
#include <vector>
#include <iostream>
using namespace std;
class Solution {
public:
/* Sol 0
* Solving recursively.
* Using an array to speed up.(DP)
*/
bool wordBreak(string s, vector<string>& wordDict) {
int *arr = new int[s.length()];
memset(arr,1,s.length()*4);
bool result = wordBreak(s,wordDict,arr,0);
delete []arr;
return result;
}
bool wordBreak(string s,vector<string>& wordDict,int *arr,int index){
if(index == s.length())
return true;
if(!arr[index]) return false;
for(const string& word : wordDict){
if(index + word.length() > s.length() || word != s.substr(index,word.length()))
continue;
bool result = wordBreak(s,wordDict,arr,index + word.length());
if(result) return true;
else arr[index + word.length()] = 0;
}
return false;
}
/* Sol 1
* Standard DP solution.
* Attention!!!
* string.length() returns an unsigned int value,
* so i - word.length() becomes unsigned value type.
* It's always non-negative.So change i - word.length() to i >= word.length() when checking.
*/
bool wordBreakDP(string s, vector<string>& wordDict){
int *arr = new int[s.length()+1];
memset(arr,0,s.length()*4 + 4);
arr[0] = 1;
for(int i = 1;i <= s.size();++i){
for(const string& word : wordDict){
if(i >= word.length() && arr[i-word.length()] && word == s.substr(i-word.length(),word.length())){
arr[i] = 1;
break;
}
}
}
return arr[s.length()];
}
};