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".

 

使用DP会比较效率地解决此问题。基本思想是: 如果S能被分割,那么存在某个位置i,使得S(0,i)能被分割且S(i+1,end)在字典里。需要双重循环,第一重循环取出子串S(0,k) (k=1,2,....end). 第二重循环在S(0,k)中判断每一个位置j是否满足S(0,j)可分割,且S(j+1,k)在字典里,如果找到满足条件的位置则跳出这重循环。

考虑到捕获到第一个单词时,S(0,j)状态还不存在,所以可以在dp数组第一位放置状态true,如此得到第一个单词时考察S(0,0)得到true,且剩余部分在字典里,满足条件,将相应dp位置为true.

代码:

 1 public boolean wordBreak(String s, Set<String> dict) {
 2         boolean[] dp = new boolean[s.length()+1];
 3         dp[0]=true;
 4         for(int i=1;i<=s.length();i++){
 5             for(int j=0;j<i;j++){
 6                 if(dp[j] && dict.contains(s.substring(j,i))){
 7                     dp[i]=true;
 8                     break;
 9                 }
10             }
11         }
12         return dp[s.length()];
13     }

 

posted on 2014-10-13 23:42  metalx  阅读(123)  评论(0编辑  收藏  举报