1
+ // Source : https://leetcode.com/problems/word-break/
2
+ // Author : henrytien
3
+ // Date : 2022年02月02日
4
+
5
+ /* ****************************************************************************************************
6
+ *
7
+ * Given a string s and a dictionary of strings wordDict, return true if s can be segmented into a
8
+ * space-separated sequence of one or more dictionary words.
9
+ *
10
+ * Note that the same word in the dictionary may be reused multiple times in the segmentation.
11
+ *
12
+ * Example 1:
13
+ *
14
+ * Input: s = "leetcode", wordDict = ["leet","code"]
15
+ * Output: true
16
+ * Explanation: Return true because "leetcode" can be segmented as "leet code".
17
+ *
18
+ * Example 2:
19
+ *
20
+ * Input: s = "applepenapple", wordDict = ["apple","pen"]
21
+ * Output: true
22
+ * Explanation: Return true because "applepenapple" can be segmented as "apple pen apple".
23
+ * Note that you are allowed to reuse a dictionary word.
24
+ *
25
+ * Example 3:
26
+ *
27
+ * Input: s = "catsandog", wordDict = ["cats","dog","sand","and","cat"]
28
+ * Output: false
29
+ *
30
+ * Constraints:
31
+ *
32
+ * 1 <= s.length <= 300
33
+ * 1 <= wordDict.length <= 1000
34
+ * 1 <= wordDict[i].length <= 20
35
+ * s and wordDict[i] consist of only lowercase English letters.
36
+ * All the strings of wordDict are unique.
37
+ ******************************************************************************************************/
38
+
39
+ #include " ../inc/ac.h"
40
+
41
+ class Solution
42
+ {
43
+ public:
44
+ bool wordBreak (string s, vector<string> &wordDict)
45
+ {
46
+ if (s.empty () || wordDict.size () == 0 )
47
+ {
48
+ return false ;
49
+ }
50
+
51
+ vector<bool > dp (s.size ()+1 ,false );
52
+ set<string> dict;
53
+ for (auto &&w : wordDict)
54
+ {
55
+ dict.insert (w);
56
+ }
57
+
58
+ dp[0 ] = true ;
59
+
60
+ for (int i = 1 ; i <= s.size (); i++)
61
+ {
62
+ for (int j = i - 1 ; j >= 0 ; j--)
63
+ {
64
+ if (dp[j])
65
+ {
66
+ string word = s.substr (j,i- j);
67
+ if (dict.find (word) != dict.end ())
68
+ {
69
+ dp[i] = true ;
70
+ break ;
71
+ }
72
+
73
+ }
74
+ }
75
+ }
76
+ return dp[s.size ()];
77
+
78
+ }
79
+ };
80
+
81
+ int main ()
82
+ {
83
+ string s = " applepenapple" ;
84
+ vector<string> word_dict{" apple" ," pen" };
85
+ cout << Solution ().wordBreak (s, word_dict) << " \n " ;
86
+ return 0 ;
87
+ }
0 commit comments