Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words.
For example, given
s =
dict =
s =
"leetcode"
,dict =
["leet", "code"]
.
Return true because
DP problem. We use dp[i] to indicate wether s[0...i] could be split by the dict or not. Then only when we find some position j that dp[j-1] == true and s[j...i] is contained in the dict, dp[i] = true. Be careful when j = 0."leetcode"
can be segmented as "leet code"
.public boolean wordBreak(String s, Setdict) { int n = s.length(); boolean[] dp = new boolean[n]; for(int i = 0; i < n; i++) { for(int j = 0; j <= i; j++) { if(j == 0) { if(dict.contains(s.substring(0, i+1)) == true) { dp[i] = true; break; } } else { if(dp[j-1] == true && dict.contains(s.substring(j, i+1)) == true) { dp[i] = true; break; } } } } return dp[n-1]; }
没有评论:
发表评论