My recursive solution with memoization.


  • 0
    J

    My recursive solution with memoization.

    HashSet<String> set = new HashSet<String>();
    public boolean wordBreak(String s, Set<String> wordDict) {
        if(s.length() == 0)
            return true;
        if(set.contains(s))
            return false;
            
        String str = "";
        for(int i = 0; i < s.length(); i++){
            str += s.charAt(i);
            if(wordDict.contains(str)){
                if(wordBreak(s.substring(i+1), wordDict))
                    return true;
            }
        }
        
        set.add(s);
        return false;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.