Created
September 24, 2014 03:21
-
-
Save sreeprasad/d23d6382b288aaf1c906 to your computer and use it in GitHub Desktop.
Word Break
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Map; | |
import java.util.HashMap; | |
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