Word Break

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 = "leetcode",
dict = ["leet", "code"].

Return true because "leetcode" can be segmented as "leet code".

 

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

 

 

 

posted @ 2014-02-22 13:13  krunning  阅读(160)  评论(0编辑  收藏  举报