Question: Suppose we have an array blocks [] of nonempty strings and we want to see whether a given target string can be made by concantenating
Suppose we have an array blocks [] of nonempty strings and we want to see whether a given target string can be made by concantenating a sublist of the blocks .
The blocks that get concatenated must be used in the same order as in they occur in the original array .
For example, if blocks [] is {"aabb", "aa", "ab", "bbb", "ba" , "baa", "bbaa" } and the target is "aabbbbbaa" then the return value would be true since we can concatenate the blocks [1], blocks [3] and blocks [6] to make the target.
On the other hand, given the same blocks , we couldn't make "bbaaaa" since that would require using blocks [6] and blocks [1] in the opposite order from their order in the array .
Implement a recursive function static boolean constructable(String [] blocks , int startIndex, String target) that returns true if and only if the target can be made by concatenating a sublist of the strings in the blocks array , from indexes startIndex to the last index (i.e. blocks .length-1).
You function will need two base cases: When the target is empty and when startIndex reaches blocks .length but the target is nonempty.
If the target is empty then we will always return true since the empty string can be made without needing to concatenate anything.
If the target is nonempty but startIndex is equal to blocks .length, we will return false since in this case there are no strings available to concatenate.
The recursive case is when the target is nonempty and startIndex is still less than blocks .length.
In this case we will need to combine two recursive calls and return true if either of those calls returns true .
To figure out what the the two recursive calls are, think about two possibilities: either we use the block at index startIndex or we don't.
To determine whether we can use a block b, call target.indexOf(b). If that returns 0 then that means the target begins with b (e.g. b is "hi" and target is "hiho").
In that case we can call constructable with target.substring(b.length()) in place of target for one of the recursive calls.
Just because we're able to use b, doesn't mean it will ultimately be used. For example, even though target starts with "aabb" in the example above, there way to construct "aabbbbbaa" by starting with that block .
As a precondition you can assume that both total and startIndex are nonnegative.
We would usually call constructable with startIndex equal to 0, since we want to know whether the target can be make using any sublilst of the blocks , not just subsets that exclude the elements at indexes 0 through startIndex-1.
programming language is JAVA:
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
