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:
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 }
原文:https://www.cnblogs.com/cnoodle/p/12880007.html