139. Word Break

Given a string s and a dictionary of strings wordDict, return true if s can be segmented into a space-separated sequence of one or more dictionary words.

Note that the same word in the dictionary may be reused multiple times in the segmentation.

Example 1:

Input: s = "leetcode", wordDict = ["leet","code"]
Output: true
Explanation: Return true because "leetcode" can be segmented as "leet code".

Example 2:

Input: s = "applepenapple", wordDict = ["apple","pen"]
Output: true
Explanation: Return true because "applepenapple" can be segmented as "apple pen apple".
Note that you are allowed to reuse a dictionary word.

Example 3:

Input: s = "catsandog", wordDict = ["cats","dog","sand","and","cat"]
Output: false

Constraints:

  • 1 <= s.length <= 300

  • 1 <= wordDict.length <= 1000

  • 1 <= wordDict[i].length <= 20

  • s and wordDict[i] consist of only lowercase English letters.

  • All the strings of wordDict are unique.

Solution

 public boolean wordBreak(String s, List<String> wordDict) {
        Map<Integer, Boolean> dp = new HashMap<>(); 
        Set<String> set = new HashSet<>();
        for(String word : wordDict){
            set.add(word);
        }
        
        return helper(s, 0, set, dp);
            
    }
    
    
    public boolean helper(String s, int start, Set<String> set, Map<Integer, Boolean> dp){
        if(start == s.length()) return true;
        if(dp.containsKey(start)) return dp.get(start);
        
        
        for(int i = start; i < s.length(); i++){
            if(set.contains(s.substring(start, i+1)) && 
                helper(s, i+1, set, dp)){
                dp.put(start, true);
                return true;
            }
        }
        dp.put(start, false);
        return false;
    }

Time Complexity : O(N^2) : Calculate (N + N-1 + N-2 + ....+1

since we only toggle all the combinaton of [0...N] // which will be N+ N-1 + N-2 + ...1 // oneChar twoChar threeChar)

Last updated

Was this helpful?