Skip to content

Commit 8c067c9

Browse files
committed
单词切分
1 parent bc06ec0 commit 8c067c9

File tree

7 files changed

+86
-0
lines changed

7 files changed

+86
-0
lines changed

LeetCode/Doc/单词切分.md

+42
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
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)
Binary file not shown.
Binary file not shown.
353 Bytes
Binary file not shown.
566 Bytes
Binary file not shown.

LeetCode/src/eleven/Solution.java

+43
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
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+
}

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -152,4 +152,5 @@
152152
- [reorder-list(链表重排序)](./LeetCode/Doc/链表重排序.md)
153153
- [linked-list-cycle-ii(找出链表中环的入口节点)](./LeetCode/Doc/找出链表中环的入口节点.md)
154154
- [linked-list-cycle(判断链表中是否存在环)](./LeetCode/Doc/判断链表中是否存在环.md)
155+
- [word-break(单词切分)](./LeetCode/Doc/单词切分.md)
155156

0 commit comments

Comments
 (0)