139. Word Break
Problem:
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 =
dict =
s =
"leetcode"
,dict =
["leet", "code"]
.
Return true because
"leetcode"
can be segmented as "leet code"
.
Analysis:
State: dp[i] s前i个字符是否满足word break
Transition: dp[i] == true, 满足 dp[j] == true && wordDict.contains(s.substring(i, j))
举个例子:
leet code
j = 4 i = 8
dp[j] 表示leet知否满足word break。 因为dp[]要比s多一位,dp[j] 对应的j指向的前一位。s.substring(4,8) == code.
Solution:
class Solution { public boolean wordBreak(String s, List<String> wordDict) { int len = s.length(); boolean[] dp = new boolean[len + 1]; dp[0] = true; for (int i = 1; i <= len; i++) { for (int j = 0; j <= i; j++) { if (dp[j] && wordDict.contains(s.substring(j, i)) { dp[i] = true; break; } } } return dp[len]; } }
评论
发表评论