word-break 1.0.0
Word Break
Loading...
Searching...
No Matches
Solution Class Reference

Public Member Functions

bool wordBreak (string s, vector< string > &wordDict)
 

Detailed Description

Definition at line 8 of file main.cpp.

Member Function Documentation

◆ wordBreak()

bool Solution::wordBreak ( string  s,
vector< string > &  wordDict 
)
inline

Definition at line 11 of file main.cpp.

12 {
13 // array to keep whether s can be segmented at each indices l e e t c o d e
14 vector<bool> array(s.length() + 1, false); // 1 0 0 0 0 0 0 0 0
15
16 // empty array can always be segmented
17 array[0] = true;
18
19 for (int i = 0; i <= (int)s.length(); ++i)
20 {
21 // s[0...i - 1] cannot be segmented
22 if (!array[i])
23 continue;
24
25 // finding all matching words (for input "leetcode", ["leet", "leets", "code"] we would have l e e t s c o d e)
26 for (string& word: wordDict) // 1 0 0 0 1 1 0 0 0 1
27 {
28 int end = i + (int)word.length();
29 // new valid word is found if whole constructed string is matching a word from dictionary
30 if (end <= (int)s.length() && s.substr(i, word.length()) == word)
31 array[end] = true;
32 }
33 }
34
35 // // dp array check
36 // for (bool el: array)
37 // cout << el << " ";
38 // cout << endl;
39
40 return array[s.length()];
41 }

Referenced by main().


The documentation for this class was generated from the following file: