Skip to content

Instantly share code, notes, and snippets.

@sreeprasad
Created July 20, 2014 14:02
Show Gist options
  • Save sreeprasad/55103c9a1ca18ef14056 to your computer and use it in GitHub Desktop.
Save sreeprasad/55103c9a1ca18ef14056 to your computer and use it in GitHub Desktop.
Word Break Solution Leet Code
public class Solution {
public boolean wordBreak(String s, Set<String> dict) {
if( (dict.size()==0)||(s.length()==0))
return false;
if(s.length()==1 && !dict.contains(s))
return false;
else if(s.length()==1 && dict.contains(s))
return true;
Set<Integer> cache = new HashSet<Integer>();
return wordBreakHelper(s,0,dict,cache);
}
public boolean wordBreakHelper(String s, int i,Set<String> dict, Set<Integer> cache){
if(dict.contains(s.substring(i)))
return true;
if(cache.contains(i))
return false;
for(int j=i;j<s.length();j++){
if(dict.contains(s.substring(i,j+1))){
if(wordBreakHelper(s,j+1,dict,cache)){
return true;
}
}
}
cache.add(i);
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment