Skip to content

Instantly share code, notes, and snippets.

@cangoal
Last active March 19, 2016 18:22
Show Gist options
  • Save cangoal/0b5675a6d37eab5a4df8 to your computer and use it in GitHub Desktop.
Save cangoal/0b5675a6d37eab5a4df8 to your computer and use it in GitHub Desktop.
LeetCode - Word Break
// backtracking : time limit exceeded
public boolean wordBreak(String s, Set<String> wordDict) {
if(s == null || s.length() == 0 || wordDict == null || wordDict.size() == 0) return false;
return helper(0, s, wordDict);
}
public boolean helper(int p, String s, Set<String> wordDict){
if(p == s.length()) return true;
for(int i=p+1; i<=s.length(); i++){
String subStr = s.substring(p, i);
if(wordDict.contains(subStr)){
if(helper(i, s, wordDict)){ // return helper(i, s, wordDict); failed case: "aaaaaaa", ["aaaa", "aaa"]
return true;
}
}
}
return false;
}
// dynamic programming
public boolean wordBreak(String s, Set<String> wordDict) {
if(s == null || s.length() == 0 || wordDict == null || wordDict.size() == 0) return false;
// ret[i] represents if substring(0, i) is valid word break
boolean[] ret = new boolean[s.length()+1];
ret[0] = true;
for(int i = 1; i <= s.length(); i++){
for(int j=0; j <= i; j++){
if(ret[j] && wordDict.contains(s.substring(j, i))){
ret[i] = true;
break;
}
}
}
return ret[s.length()];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment