1

I have been struggling with this problem all week. The problem is as follows, given such a string, S, of n uppercase letters, describe an efficient way of breaking it into a sequence of valid English words. You may assume the valid(s) function runs in O(1) time. Example of how it should work is like this. Lets say you are given CABIN as input. [A, BIN, IN, CAB, CABIN] are valid words. Function should return [[CAB, IN], [CABIN]].

I managed to get a recursive function working but can't seem to figure out how to create a dynamic solution.

Recursive Implementation (JS)

var test = 'ABORTTHEPLANMEETATTHEDARKCABIN';
var words = {
    ABORT: true,
    THE: true,
    PLAN: true,
    MEET: true,
    AT: true,
    DARK: true,
    CABIN: true
};
var valid = function(word) {
    if (words[word]) return true;
    return false;
};
String.prototype.suffix = function(i) {
    return this.substring(this.length - i);
};

String.prototype.prefix = function(i) {
    return this.substring(0, i);
};


var breakCode = function(S) {
    var T = [];

    for (var i = 1; i <= S.length; i++) {
        var str = S.suffix(i);
        if (valid(str)) {
            if (i < S.length) {
                var prefix = S.prefix(S.length - i);
                var P = breakCode(prefix);
                P.forEach(function(p) {
                    p.push(str);
                    T.push(p);
                });
            } else {
                T.push([str]);
            }
        }
    }
    return T;
}

Non Working Attempt at DP Solution

var breakCodeDP = function(S) {
    var T=[];

    for (var i = 1; i <= S.length; i++) {
        for (var j = 1; j <= i; j++) {
            var str = S.suffix(j);
            if (valid(str)) {
                if (j < i) {
                    var P = T[i - j];
                    // console.log(T);
                    // P = typeof P === 'undefined'?[]:P;
                    // P.forEach(function(p) {
                    //   if (!Array.isArray(T[i])) T[i] = [];
                    //     T[i].push([p, str]);
                    // });
                } else {
                    T[i] = [str];
                }
            }
        }
    }
}
Daniel Kobe
  • 9,376
  • 15
  • 62
  • 109
  • 1
    please give an example of what the input and output should be – François Richard Dec 14 '15 at 18:11
  • please add `suffix()` and `valid()`. – Nina Scholz Dec 14 '15 at 18:12
  • Can you clarify what you are allowed to use as part of the 'top-down DP approach'. There seems to be some confusion over the terms (see http://stackoverflow.com/questions/6164629/dynamic-programming-and-memoization-bottom-up-vs-top-down-approaches). Couldn't you just memoize your recursive solution? – Stuart Dec 14 '15 at 19:31
  • Sure. The solution should use loops where as a memoized solution would still use recursion. – Daniel Kobe Dec 14 '15 at 20:02

0 Answers0