[LeetCode每日一题]139. Word Break

题目如下:

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.

Example:

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

139. Word Break
给定一个字符串s和一个字典wordDict,判断s是否可以由字典中的词组成。
这道题可以用动态规划解决,设dp[i]表示长度为i的字符是否满足条件,求解该值需要进行一层循环,变量j从1递增到max(i,最长单词的长度),dp[i]为真的条件是dp[j]==true&&s.subString(i-j,j)在字典中。
实现代码如下:

  1. class Solution {
  2. public boolean wordBreak(String s, List<String> wordDict) {
  3. int len = s.length();
  4. boolean[] dp = new boolean[len + 1];
  5. int maxLen = 0;
  6. for (String word : wordDict) {
  7. maxLen = Math.max(maxLen, word.length());
  8. }
  9. dp[0] = true;
  10. Set<String> dict = new HashSet<>();
  11. dict.addAll(wordDict);
  12. for (int i = 1; i <= len; i++) {
  13. for (int j = 1; j <= i && j <= maxLen; j++) {
  14. if (dp[i - j] && dict.contains(s.substring(i-j, i))) {
  15. dp[i] = true;
  16. break;
  17. }
  18. }
  19. }
  20. return dp[len];
  21. }
  22. }

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注