File tree 7 files changed +86
-0
lines changed
7 files changed +86
-0
lines changed Original file line number Diff line number Diff line change
1
+ # word-break(单词切分)
2
+
3
+ <center >知识点:动态规划</center >
4
+
5
+
6
+ ## 题目描述
7
+
8
+ Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words.
9
+
10
+ For example, given
11
+ s ="leetcode",
12
+ dict =[ "leet", "code"] .
13
+
14
+ Return true because"leetcode"can be segmented as"leet code".
15
+
16
+ -----
17
+
18
+ 给定一个字符串s和一个词典,判断s是否可以被切割成一个或者多个词典中的单词。
19
+
20
+ 比如,给定s="leetcode",dict=[ "leet","code"] ,应该返回true,因为"leetcode"可以被切分成"leet"和"code"两个片段。
21
+
22
+ ## 解题思路
23
+
24
+ 使用动态规划,假设$f(j)$的真值表示$s[ 0,j] $是否可以被分词,则:
25
+ $f(n)=f(i)\&\& f(i+1,n)$
26
+ 那么如果我们要求$f(n)$是否可以被分词,我们首先需要求出$f(i)$,然后再对$s[ i+1,n] $的字符串判断是否可以分词,要求$f(i)$,又要让$j$从0开始到$i-1$,判断$f(j)$为真且$f(j,i)$为真…
27
+
28
+ 伪代码如下:
29
+
30
+ ```
31
+ 假设s的长度为length,使用array[length+1]代表f(i)到f(n)的真值,则:
32
+ 初始array[0]=true:
33
+ for i in 0 to length:
34
+ for j in 0 to i:
35
+ if array[j]&&dict.contains(s[j:i]):
36
+ array[i]=true;
37
+ return array[length]
38
+ ```
39
+
40
+ ## 代码
41
+
42
+ [ 这里] ( ../src/eleven/Solution.java )
Original file line number Diff line number Diff line change
1
+ package eleven ;
2
+
3
+ import java .util .HashSet ;
4
+ import java .util .Set ;
5
+
6
+ /**
7
+ * @author dmrfcoder
8
+ * @date 2019/4/10
9
+ */
10
+ public class Solution {
11
+ public boolean wordBreak (String s , Set <String > dict ) {
12
+ if (s == null ) {
13
+ return false ;
14
+ }
15
+
16
+ int sLength = s .length ();
17
+ boolean [] array = new boolean [sLength + 1 ];
18
+ array [0 ] = true ;
19
+
20
+
21
+ for (int index = 0 ; index <= sLength ; index ++) {
22
+ for (int index2 = 0 ; index2 < index ; index2 ++) {
23
+ for (String dictItem : dict ) {
24
+ if (s .substring (index2 , index ).equals (dictItem ) && array [index2 ]) {
25
+ array [index ] = true ;
26
+ }
27
+ }
28
+ }
29
+
30
+ }
31
+
32
+
33
+ return array [sLength ];
34
+ }
35
+
36
+ public static void main (String [] args ) {
37
+ Set <String > dict = new HashSet <>();
38
+ dict .add ("aaa" );
39
+ dict .add ("aaaa" );
40
+ Solution solution = new Solution ();
41
+ System .out .println (solution .wordBreak ("aaaaaaa" , dict ));
42
+ }
43
+ }
Original file line number Diff line number Diff line change 152
152
- [ reorder-list(链表重排序)] ( ./LeetCode/Doc/链表重排序.md )
153
153
- [ linked-list-cycle-ii(找出链表中环的入口节点)] ( ./LeetCode/Doc/找出链表中环的入口节点.md )
154
154
- [ linked-list-cycle(判断链表中是否存在环)] ( ./LeetCode/Doc/判断链表中是否存在环.md )
155
+ - [ word-break(单词切分)] ( ./LeetCode/Doc/单词切分.md )
155
156
You can’t perform that action at this time.
0 commit comments