Given a word and a dictionary, determine if it can be composed by concatenating words from the given dictionary.
Assumptions
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<String> set = new HashSet<>(Arrays.asList(dict)); return helper(input, set, 0); } private boolean helper(String input, Set<String> 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; } }
原文:https://www.cnblogs.com/xuanlu/p/13123564.html