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"
.
大致就是判断:是否字典里的几个词可以串联组成给定的String。
解题过程:
算法不太精通,最开始考虑的就是既然要找下去,那每个结果都不能落下,利用递归可以按照string长度不断递增,在前面把存在于字典的删去,然后再在剩余的里面判断是否可以由字典里的词组成,实现如下:
public class Solution { public boolean wordBreak(String s, Set<String> wordDict) { if(s == null || wordDict == null) return false; boolean result = false; int len = s.length(); if(wordDict.contains(s)) return true; for(int i = len-1; i >= 0; i--){ String word = s.substring(0,i); String rest = s.substring(i,len); if(wordDict.contains(word)){ result = result || wordBreak(rest, wordDict); } } return result; } }
然后接酱紫了:- -|||
Status: Time Limit Exceeded
Last executed input:
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab"
["a","aa","aaa","aaaa","aaaaa","aaaaaa","aaaaaaa","aaaaaaaa","aaaaaaaaa","aaaaaaaaaa"]
然后就直接没有思路了,上网查询吧。。。
大家都说可以用动态规划DP做,我自己不是很擅长找最优子结构,然后就看了一眼,里面提到可以用一个一维布尔数组来维护,数组t长度为s.length()+1,t[i]表示 0 到 i-1 是否可以用字典组成(这里指数组序号),逐步进行下去就可以完成,结果是t[s.length()]。我的理解就是可以用它来记录状态,逐步进行下去就可以省略了递归,毕竟可以用之前记录的状态,对于动态规划还是欠缺理解啊。我的自己实现如下:
public class Solution { public boolean wordBreak(String s, Set<String> wordDict) { // t[i]==true => 0-(i-1) can be segmented using dictionary // t[0]=true boolean t[] = new boolean[s.length()+1]; t[0] = true; for(int i = 1; i < s.length()+1; i++){ t[i]=false; if(wordDict.contains(s.substring(0,i))){ t[i] = true; continue; }else{ for(int j = 1; j < i; j++){ if(t[j]&&wordDict.contains(s.substring(j,i))){ t[i] = true; break; } } } } return t[s.length()]; } }
一会要好好去理解下DP了,我的参考网站如下:
http://www.programcreek.com/2012/12/leetcode-solution-word-break/
欢迎调教。。。。(我好污啊