题目:http://oj.leetcode.com/problems/word-break/
思路:
DP,res[i] 的 boolean 数组记录第 ith 位可否被 break。res[ j ] && wordDict.contains( s.substring( j , i+1 )) 判断第 ith 位可否被 break。遍历检测,知道 string 的最后一位。
参考:http://blog.csdn.net/linhuanmars/article/details/22358863
Code:
public boolean wordBreak(String s, Set<String> wordDict) {
if(s.length() == 0 || s == null) return true;
boolean[] res = new boolean[s.length()+1];
res[0] = true;
for(int i=0; i<s.length();i++){
StringBuilder str = new StringBuilder(s.substring(0,i+1));
for(int j=0; j<=i; j++){
if(res[j] && wordDict.contains(str.toString())){
res[i+1]=true;
break;
}
str.deleteCharAt(0);
}
}
return res[s.length()];
}
备注:
substring 方法都为小写
substring 在 JDK6 复制整个字符串,会引起内存 overload,JDK7 已修复,故使用 StringBuilder