Timeline Dynamic Programming Topic:
dp[i] indicates whether the prefix s[0…i-1] can be successfully split into words from the dictionary. dp[0] = true, meaning the empty string can be split. dp[The condition for dp[i] to be true is that dp[j](0 <= j < i)is true, and s.substr(j, i-j) is a word in wordDict.
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 #include <string> #include <vector> #include <unordered_set> using std::vector;using std::string;using std::unordered_set;class Solution { public : bool wordBreak (string s, vector<string> &wordDict) { int i, j, n = s.size (); unordered_set<string> dict (wordDict.begin(), wordDict.end()) ; vector<bool > dp (n + 1 , false ) ; dp[0 ] = true ; for (i = 1 ; i <= n; i++) { for (j = 0 ; j < i; j++) { if (dp[j] && dict.count (s.substr (j, i - j))) { dp[i] = true ; break ; } } } return dp[n]; } };
LeetCode Hot 100 rewrite: using prefix tree + BFS approach
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 #include <string> #include <vector> #include <queue> using std::vector;using std::string;using std::queue;struct TrieNode { vector<TrieNode *> children; char data; bool is_end; TrieNode () { this ->children = vector <TrieNode *>(26 , nullptr ); this ->is_end = false ; } }; class Solution { public : bool wordBreak (string s, vector<string> &wordDict) { TrieNode *root = new TrieNode, *p; int i, n = s.size (); for (string word : wordDict) { p = root; for (char ch : word) { if (p->children[ch - 'a' ] == nullptr ) p->children[ch - 'a' ] = new TrieNode; p = p->children[ch - 'a' ]; p->data = ch; } p->is_end = true ; } queue<int > que; vector<bool > visited (n, false ) ; que.push (0 ); visited[0 ] = true ; while (!que.empty ()) { int start = que.front (); que.pop (); if (start == n) return true ; p = root; for (i = start; i < n; i++) { if (p->children[s[i] - 'a' ] == nullptr ) break ; p = p->children[s[i] - 'a' ]; if (p->is_end && !visited[i + 1 ]) { que.push (i + 1 ); visited[i + 1 ] = true ; } } } return false ; } };