[Leetcode] 139 Word Break, leetcode139
This problem can be done with DFS, but the better way is to use DP. This type of DP still has little contact.
Only words in the source string must be in the dictionary. Therefore, we can use dp [I] to indicate that the first I characters of the source string can be separated, the condition that dp [j] satisfies the division is that k (0 <= k <= j) makes dp [k] & s [k + 1, j] in the dictionary. Note the subscript problem, dp [I] refers to the first I characters, the corresponding letter is s [I-1].
Class Solution {public: bool wordBreak (string s, unordered_set <string> & wordDict) {int len = s. length (); vector <int> dp (len + 1, 0); dp [0] = 1; for (int I = 1; I <= len; I ++) {for (int j = I-1; j> = 0; j --) {if (dp [j] = 1 & wordDict. count (s. substr (j, I-j) {dp [I] = 1; break ;}} return dp [len] ;}};We also see a solution of Trie: http://www.cnblogs.com/x1957/p/3492926.html for your reference.
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.