首页 > 其他 > 详细

[LeetCode] 139. Word Break

时间:2020-05-13 09:38:24      阅读:58      评论:0      收藏:0      [点我收藏+]

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

单词拆分。题意是给一个String s和一个包含一些单词的list,请你返回用这些list里面的单词是否能拼接成S。

思路是DP,DP[i]的含义是以字母i结尾的字符串是否能被list中的单词拼接。初始化dp[0] = true。

时间O(n^2)

空间O(n)

Java实现

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

 

LeetCode 题目总结

[LeetCode] 139. Word Break

原文:https://www.cnblogs.com/cnoodle/p/12880007.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!