Java simple recursing with memorization


  • 1
    W
    class Solution {
        Set<String> cacheNo = new HashSet();
        
        public boolean wordBreak(String s, List<String> wordDict) {
            if (s.length() == 0) return true;
            if (cacheNo.contains(s)) return false;
            
            for (String word : wordDict) {
                if (s.startsWith(word)) {
                    if (wordBreak(s.substring(word.length()), wordDict)) {
                        return true;
                    }
                }
            }
            
            cacheNo.add(s);
            return false;
        }
    }
    

Log in to reply
 

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