leetcode 139. word break

139. Word Break

Difficulty:: Medium

Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words.

Note:

  • The same word in the dictionary may be reused multiple times in the segmentation.
  • You may assume the dictionary does not contain duplicate words.

Example 1:

1
2
3
Input: s = "leetcode", wordDict = ["leet", "code"]
Output: true
Explanation: Return true because "leetcode" can be segmented as "leet code".

Example 2:

1
2
3
4
Input: s = "applepenapple", wordDict = ["apple", "pen"]
Output: true
Explanation: Return true because "applepenapple" can be segmented as "apple pen apple".
Note that you are allowed to reuse a dictionary word.

Example 3:

1
2
Input: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"]
Output: false

Solution

Language: Java

DFS解法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class  {
public boolean wordBreak(String s, List<String> wordDict) {
return dfsHelper(s, new HashSet(wordDict), 0, new Boolean[s.length()]);
}

public boolean dfsHelper(String s, Set<String> wordDict, int start, Boolean[] memo) {
if (start == s.length()) {
return true;
}
if (memo[start] != null) {
return memo[start];
}
for (int end = start + 1; end <= s.length(); end++) {
if (wordDict.contains(s.substring(start, end)) && dfsHelper(s, wordDict, end, memo)) {
return memo[start] = true;
}
}
return memo[start] = false;
}
}

DP解法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class  {
public boolean wordBreak(String s, List<String> wordDict) {
Set<String> wordDictSet=new HashSet(wordDict);
boolean[] dp = new boolean[s.length() + 1];
dp[0] = true;
for (int i = 1; i <= s.length(); i++) {
for (int j = 0; j < i; j++) {
if (dp[j] && wordDictSet.contains(s.substring(j, i))) {
dp[i] = true;
break;
}
}
}
return dp[s.length()];
}
}

55%

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class  {
public boolean wordBreak(String s, List<String> wordDict) {
if (s == null || wordDict == null) {
return false;
}
Set<String> wordSet = new HashSet<>(wordDict);
boolean[] dp = new boolean[s.length() + 1];
dp[0] = true;
for (int i = 0; i < s.length(); i++) {
for (int j = i + 1; j <= s.length(); j++) {
if (dp[i] && wordDict.contains(s.substring(i, j))) {
dp[j] = true;
}
}
}
return dp[s.length()];
}
}