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. You may assume the dictionary does not contain duplicate words.
For example, given
s ="leetcode"
,
dict =["leet", "code"]
.Return true because
"leetcode"
can be segmented as"leet code"
.题目大意:给定一个非空字符串s与一个字典wordDict,判断石头能用字典中的字符组成非空字符串
思路:DP,dp[i]表示s的前i个字符是否能由字典中的字符组成
代码
package DP; import java.util.List; /** * @Author OovEver * @Date 2017/12/17 16:32 */ public class LeetCode139 { public boolean wordBreak(String s, List<String> 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] && wordDict.contains(s.substring(j, i))) { dp[i] = true; break; } } } return dp[s.length()]; } }