If the word consists of two valid words

Given the dictionary, find out if a given word can be spoken in two words in a dictionary. E.g. given the "newspaper", you should find if this can be done in a nutshell. (news and paper in this case). The only thing I can think of is to start from the beginning and check if the current line is a word. In this case, checking n, ne, new, news ..... checks the rest if the current line is a valid word.

Also, how do you generalize it to k (meaning a word consists of k words)? Any thoughts?

+1
source share
3 answers

Running a split in the center can lead to faster results. For example, for a newspaper, you will first try to crack in a “newspaper” or “news newspaper”. As you can see, for this example you will find your result on the first or second attempt. If you don’t find the result, just search outside. See the example for the "crossbow" below:

cros sbow
cro ssbow
cross bow
+1
source

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) {
     /* Base case: If the string is empty, we can only split into k words and vice-
      * versa.
      */
     if (word.isEmpty() || k == 0)
         return word.isEmpty() && k == 0;

     /* Generate all possible non-empty splits of the word into two parts, recursing on
      * problems where the first word is known to be valid.
      *
      * This loop is structured so that we always try pulling off at least one letter
      * from the input string so that we don't try splitting the word into k pieces
      * of which some are empty.
      */
     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;
     }

     /* If we're here, then no possible split works in this case and we should signal
      * that no solution exists.
      */
     return false;
 }

 }

O (n k), k . , , - .

+1

, strpos (-like), , . , . - :

  • , , , "", "" "".
  • , + == , , + .., + ==, .

, , , ( ), , , .

, " k".

0
source

Source: https://habr.com/ru/post/1791133/


All Articles