Split a string to a string of valid words using Dynamic Programming

后端 未结 6 1192
不知归路
不知归路 2020-12-23 15:02

I need to find a dynamic programming algorithm to solve this problem. I tried but couldn\'t figure it out. Here is the problem:

You are given a string of n character

6条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-23 15:37

    The string s[] can potentially be split into more than one ways. The method below finds the maximum number of words in which we can split s[]. Below is the sketch/pseudocode of the algorithm

    bestScore[i] -> Stores the maximum number of words in which the first i characters can be split (it would be MINUS_INFINITY otherwise)

    for (i = 1 to n){
         bestScore[i] = MINUS_INFINITY
         for (k = 1 to i-1){
            bestScore[i] = Max(bestSCore[i], bestScore[i-k]+ f(i,k))
         }
     }
    

    Where f(i,k) is defined as:

    f(i,k) = 1 : if s[i-k+1 to i] is in dictionary
           = MINUS_INFINITY : otherwise
    

    bestScore[n] would store the maximum number of words in which s[] can be split (if the value is MINUS_INFINIY, s[] cannot be split)

    Clearly the running time is O(n^2)

    As this looks like a textbook exercise, I will not write the code to reconstruct the actual split positions.

提交回复
热议问题