In the case of two words, the problem can be solved simply by considering all possible ways of breaking the word into two, then checking each half to see if it is a real word. If the input string is of length n, then there are only O (n) different ways of splitting the string. If you save the rows in a structure that supports quick searches (say, trie or hash table).
- k > 2 , . :
k , , , k - 1 .
, , , .
, , . , , , k - 1 . , , , . , Java:
public static boolean isSplittable(String word, int k, Set<String> dictionary) {
if (word.isEmpty() || k == 0)
return word.isEmpty() && k == 0;
for (int i = 1; i <= word.length(); ++i) {
String first = word.substring(0, i), last = word.substring(i);
if (dictionary.contains(first) &&
isSplittable(last, k - 1, dictionary)
return true;
}
return false;
}
}
O (n k), k . , , - .