Skip to content

Commit 2c41774

Browse files
author
applewjg
committed
Word Break
Change-Id: Ib9573f25a92cb9f43bb03f7d304740199407c4d3
1 parent c4271e5 commit 2c41774

File tree

2 files changed

+82
-0
lines changed

2 files changed

+82
-0
lines changed

WordBreak.java

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/*
2+
Author: Andy, nkuwjg@gmail.com
3+
Date: Jan 26, 2015
4+
Problem: Word Break
5+
Difficulty: Easy
6+
Source: http://oj.leetcode.com/problems/word-break/
7+
Notes:
8+
Given a string s and a dictionary of words dict, determine if s can be segmented into
9+
a space-separated sequence of one or more dictionary words.
10+
For example, given
11+
s = "leetcode",
12+
dict = ["leet", "code"].
13+
Return true because "leetcode" can be segmented as "leet code".
14+
15+
Solution: dp.
16+
*/
17+
18+
public class Solution {
19+
public boolean wordBreak(String s, Set<String> dict) {
20+
int n = s.length();
21+
boolean[] dp = new boolean[n+1];
22+
dp[n] = true;
23+
for (int i = n - 1; i >= 0; --i) {
24+
for (int j = i; j < n; ++j) {
25+
if (dict.contains(s.substring(i,j+1)) && dp[j+1]) {
26+
dp[i] = true;
27+
break;
28+
}
29+
}
30+
}
31+
return dp[0];
32+
}
33+
}

WordBreakII.java

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
/*
2+
Author: Andy, nkuwjg@gmail.com
3+
Date: Jan 29, 2015
4+
Problem: Word Break II
5+
Difficulty: Easy
6+
Source: http://oj.leetcode.com/problems/word-break-ii/
7+
Notes:
8+
Given a string s and a dictionary of words dict, add spaces in s to
9+
construct a sentence where each word is a valid dictionary word.
10+
Return all such possible sentences.
11+
For example, given
12+
s = "catsanddog",
13+
dict = ["cat", "cats", "and", "sand", "dog"].
14+
A solution is ["cats and dog", "cat sand dog"].
15+
16+
Solution: check before constructing the sentences.
17+
*/
18+
19+
public class Solution {
20+
public List<String> wordBreak(String s, Set<String> dict) {
21+
List<String> res = new ArrayList<String>();
22+
int n = s.length();
23+
boolean[] canBreak = new boolean[n+1];
24+
canBreak[n] = true;
25+
for (int i = n - 1; i >= 0; --i) {
26+
for (int j = i; j < n; ++j) {
27+
if (dict.contains(s.substring(i,j+1)) && canBreak[j+1]) {
28+
canBreak[i] = true;
29+
break;
30+
}
31+
}
32+
}
33+
if (canBreak[0] == false) return res;
34+
wordBreakRe(s, dict, "", 0, res);
35+
return res;
36+
}
37+
public void wordBreakRe(String s, Set<String> dict, String path, int start, List<String> res) {
38+
if (start == s.length()) {
39+
res.add(path);
40+
return;
41+
}
42+
if (path.length() != 0) path = path + " ";
43+
for (int i = start; i < s.length(); ++i) {
44+
String word = s.substring(start, i + 1);
45+
if (dict.contains(word) == false) continue;
46+
wordBreakRe(s, dict, path + word, i + 1, res);
47+
}
48+
}
49+
}

0 commit comments

Comments
 (0)