Skip to content

Instantly share code, notes, and snippets.

@wangchauyan
Last active October 13, 2019 15:11
Show Gist options
  • Save wangchauyan/a07fdc7971a3c76d5aa9 to your computer and use it in GitHub Desktop.
Save wangchauyan/a07fdc7971a3c76d5aa9 to your computer and use it in GitHub Desktop.
Word Break
/*
Give a string, and a dictionary, find out if this string could be segmented by a space which's substring
are in this dictionary.
For example, String "leetcode", dictionary ["leet", "code"],
then return true, cause this string could be segmented as "leet code";
*/
public class Solution {
public boolean wordBreak(String str, Set<String> dict) {
// DP problem.
boolean[] array = new boolean[str.length()+1];
array[0] = true;
for(int i = 0; i < str.length(); i++) {
StringBuffer tempString = new StringBuffer(str.substring(0, i+1));
for(int j = 0; j <= i; j++) {
if(array[j] && dict.contains(tempString.toString())) {
array[i+1] = true;
break;
}
tempString.deleteCharAt(0);
}
}
return array[str.length()];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment