LeetCode-139-Word-Break

单词拆分

Question

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:

Input: s = “leetcode”, wordDict = [“leet”, “code”]
Output: true
Explanation: Return true because “leetcode” can be segmented as “leet code”.

Example 2:

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:

Input: s = “catsandog”, wordDict = [“cats”, “dog”, “sand”, “and”, “cat”]
Output: false

Solution

采用动态规划(DP)

  • 使用dp动态规划来处理,将问题拆分有关联的子问题
  • 例如dp[i]表示s[:i]是否可以被分词且都在字典数组中
  • 在 dp[j] == 1, j>=0, j<i 的情况下,只要满足s[j:i]出现在字典数组中,则 dp[i] = 1 是成立的
  • 所以需要处理下第一个边界,后面就可以用上述公式来推算出来

Runtime: 3 ms, faster than 97.51% of Java online submissions for Word Break.
Memory Usage: 36.8 MB, less than 69.21% of Java online submissions for Word Break.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public boolean wordBreak(String s, List<String> wordDict) {
boolean[] dp = new boolean[s.length()];
for (int i = 0; i < s.length(); ++i) {
for (int j = 0; j < wordDict.size(); ++j) {
String w = wordDict.get(j);
int l = w.length();
if (
i + 1 >= l && s.substring(i+1-l, i+1).equals(w) && (i+1-l ==0 || dp[i - l] == true ) // fix the first time
) {
dp[i] = true;
break;
}
}
}

return dp[s.length() - 1] == true;
}
}
原创技术分享,您的支持将鼓励我继续创作