File tree Expand file tree Collapse file tree 1 file changed +59
-0
lines changed Expand file tree Collapse file tree 1 file changed +59
-0
lines changed Original file line number Diff line number Diff line change 1+ class  Solution  {
2+     class  TrieNode 
3+     {
4+         public: 
5+         TrieNode* next[26 ];
6+         bool  end;
7+         TrieNode ()
8+         {
9+             end = false ;
10+             for  (int  i=0 ;i<26 ;i++)
11+                 next[i] = NULL ;
12+         }
13+     };
14+     TrieNode* root;
15+     int  memo[300 ];
16+ public: 
17+     bool  wordBreak (string s, vector<string>& wordDict) 
18+     {
19+         root = new  TrieNode ();
20+         for  (auto  word: wordDict)
21+         {
22+             TrieNode* node = root;
23+             for  (auto  ch: word)
24+             {
25+                 if  (node->next [ch-' a'  ]==NULL )
26+                     node->next [ch-' a'  ] = new  TrieNode ();
27+                 node = node->next [ch-' a'  ];
28+             }
29+             node->end  = true ;
30+         }
31+         
32+         return  dfs (s,0 );          
33+     }
34+     
35+     bool  dfs (string&s, int  cur)
36+     {
37+         if  (memo[cur]==1 ) return  false ;
38+         
39+         if  (cur==s.size ())
40+             return  true ;
41+         
42+         TrieNode* node = root;
43+         for  (int  i=cur; i<s.size (); i++)
44+         {           
45+             if  (node->next [s[i]-' a'  ]!=NULL )
46+             {
47+                 node = node->next [s[i]-' a'  ];
48+                 if  (node->end ==true  && dfs (s, i+1 ))
49+                     return  true ;
50+             } else 
51+             {
52+                 break ;
53+             }
54+         }
55+         
56+         memo[cur] = 1 ;
57+         return  false ;
58+     }
59+ };
    
 
   
 
     
   
   
          
     
  
    
     
 
    
      
     
 
     
    You can’t perform that action at this time.
  
 
    
  
     
    
      
        
     
 
       
      
     
   
 
    
    
  
 
  
 
     
    
0 commit comments