[Algo] 99. Dictionary Word I


Given a word and a dictionary, determine if it can be composed by concatenating words from the given dictionary.

Assumptions

  • The given word is not null and is not empty
  • The given dictionary is not null and is not empty and all the words in the dictionary are not null or empty

Examples

Dictionary: {“bob”, “cat”, “rob”}

  • Word: “robob” return false

  • Word: “robcatbob” return true since it can be composed by "rob", "cat", "bob"

public class Solution {
  public boolean canBreak(String input, String[] dict) {
    Set set = new HashSet<>(Arrays.asList(dict));
    return helper(input, set, 0);
  }

  private boolean helper(String input, Set set, int index) {
    if (index == input.length()) {
      return true;
    }
    for (int i = index; i < input.length(); i++) {
      // substring need to be i + 1
      if (set.contains(input.substring(index, i + 1)) && helper(input, set, i + 1)) {
        return true;
      }
    }
    return false;
  }
}
dfs