[LeetCode] Word Break
Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words.
For example, given
s = "leetcode"
,
dict = ["leet", "code"]
.
Return true because "leetcode"
can be segmented as "leet code"
.
1 #include <iostream> 2 #include <string> 3 #include <set> 4 #include <cstdio> 5 6 using namespace std; 7 8 set<string> myset; 9 bool ** pmatrix = NULL; 10 11 template<typename T> 12 void BuildMatrix(T *** pmaze,unsigned row_num,unsigned column_num) 13 { 14 *pmaze = new T*[row_num]; 15 for(unsigned i=0;i<row_num;++i){ 16 (*pmaze)[i] = new T[column_num]; 17 } 18 } 19 20 template<typename T> 21 void ReleaseMatrix(T ***pmaze,unsigned row_num) 22 { 23 if(!pmaze) return; 24 25 for(unsigned i=0;i<row_num;++i){ 26 delete [](*pmaze)[i]; 27 } 28 29 delete [](*pmaze); 30 } 31 32 bool FindWord(int length){ 33 int i=0,j=0; 34 for(j=i;j<length;++j){ 35 if(pmatrix[i][j]){ 36 if(j==length-1) return true; 37 else i = j+1; 38 } 39 } 40 41 return false; 42 } 43 44 void Solve(){ 45 myset.clear(); 46 47 string strtomatch; 48 int dicwordnum = 0; 49 cin>>dicwordnum; 50 51 for(int i=0;i<dicwordnum;++i){ 52 cin>>strtomatch; 53 myset.insert(strtomatch); 54 } 55 56 cin>>strtomatch; 57 unsigned strlength = strtomatch.length(); 58 59 BuildMatrix(&pmatrix,strlength,strlength); 60 61 for(int i=0;i<strlength;++i){ 62 for(int j=i;j<strlength;++j){ 63 pmatrix[i][j] = false; 64 } 65 } 66 67 for(unsigned i=0;i<strlength;++i){ 68 for(unsigned j=i;j<strlength;++j){ 69 string strdata; 70 strdata.assign(strtomatch,i,j-i+1); 71 if(myset.find(strdata)!=myset.end()){ 72 pmatrix[i][j] = true; 73 } 74 } 75 } 76 77 for(int i=strlength-1;i>=0;--i){ 78 bool isallfalse = true; 79 for(int j = i;j<strlength;++j){ 80 if(pmatrix[i][j]){ 81 isallfalse = false; 82 break; 83 } 84 } 85 86 if(isallfalse&&(i-1>=0)){ 87 for(int j = 0;j<strlength;++j){ 88 pmatrix[j][i-1] = false; 89 } 90 } 91 } 92 93 if(FindWord(strlength)) cout<<"true"<<endl; 94 else cout<<"false"<<endl; 95 96 ReleaseMatrix(&pmatrix,strtomatch.length()); 97 } 98 99 int main() 100 { 101 freopen("txt.in","r",stdin); 102 freopen("txt.out","w",stdout); 103 104 int case_num = 0; 105 cin>>case_num; 106 107 for(int i=0;i<case_num;++i){ 108 cout<<"Case "<<i+1<<": "; 109 Solve(); 110 } 111 112 return 0; 113 }
txt.in
7 1 a a 2 what is whats 3 hello nice to helloto 5 Kobe Carter LeBron Jordan Iverson Yao 4 ab c abcd e abcde 3 car ca rs cars 2 aaaa aa aaaaaaa
txt.out
Case 1: true Case 2: false Case 3: true Case 4: false Case 5: true Case 6: true Case 7: false