word-break 1.0.0
Word Break
Loading...
Searching...
No Matches
main.cpp
Go to the documentation of this file.
1#include <iostream>
2#include <vector>
3#include <string>
4#include <unordered_set>
5
6using namespace std;
7
9{
10public:
11 bool wordBreak(string s, vector<string>& wordDict)
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 }
42};
43
44int main()
45{
46 // string input = "catsandog";
47 // vector<string> dictionary = {"cats","dog","sand","and","cat"};
48 string input = "leetcode";
49 vector<string> dictionary = {"leet", "code"};
50 Solution sol;
51 cout << "output: " << sol.wordBreak(input, dictionary) << endl;
52 return 0;
53}
bool wordBreak(string s, vector< string > &wordDict)
Definition main.cpp:11
int main()
Definition main.cpp:44