-
Notifications
You must be signed in to change notification settings - Fork 1
/
Word Break.cpp
84 lines (66 loc) · 1.67 KB
/
Word Break.cpp
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
class Solution {
public:
bool ** pmatrix = NULL;
template<typename T>
void BuildMatrix(T *** pmaze,unsigned row_num,unsigned column_num)
{
*pmaze = new T*[row_num];
for(unsigned i=0;i<row_num;++i){
(*pmaze)[i] = new T[column_num];
}
}
template<typename T>
void ReleaseMatrix(T ***pmaze,unsigned row_num)
{
if(!pmaze) return;
for(unsigned i=0;i<row_num;++i){
delete [](*pmaze)[i];
}
delete [](*pmaze);
}
bool FindWord(int length){
int i=0,j=0;
for(j=i;j<length;++j){
if(pmatrix[i][j]){
if(j==length-1) return true;
else i = j+1;
}
}
return false;
}
bool wordBreak(string strtomatch, unordered_set<string> &myset) {
unsigned strlength = strtomatch.length();
BuildMatrix(&pmatrix,strlength,strlength);
for(int i=0;i<strlength;++i){
for(int j=i;j<strlength;++j){
pmatrix[i][j] = false;
}
}
for(unsigned i=0;i<strlength;++i){
for(unsigned j=i;j<strlength;++j){
string strdata;
strdata.assign(strtomatch,i,j-i+1);
if(myset.find(strdata)!=myset.end()){
pmatrix[i][j] = true;
}
}
}
for(int i=strlength-1;i>=0;--i){
bool isallfalse = true;
for(int j = i;j<strlength;++j){
if(pmatrix[i][j]){
isallfalse = false;
break;
}
}
if(isallfalse&&(i-1>=0)){
for(int j = 0;j<strlength;++j){
pmatrix[j][i-1] = false;
}
}
}
bool ret = FindWord(strlength);
ReleaseMatrix(&pmatrix,strtomatch.length());
return ret;
}
};