-
Notifications
You must be signed in to change notification settings - Fork 19.9k
/
Copy pathAllConstruct.java
61 lines (52 loc) · 2.28 KB
/
AllConstruct.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package com.thealgorithms.dynamicprogramming;
import java.util.ArrayList;
import java.util.List;
/**
* This class provides a solution to the "All Construct" problem.
*
* The problem is to determine all the ways a target string can be constructed
* from a given list of substrings. Each substring in the word bank can be used
* multiple times, and the order of substrings matters.
*
* @author Hardvan
*/
public final class AllConstruct {
private AllConstruct() {
}
/**
* Finds all possible ways to construct the target string using substrings
* from the given word bank.
* Time Complexity: O(n * m * k), where n = length of the target,
* m = number of words in wordBank, and k = average length of a word.
*
* Space Complexity: O(n * m) due to the size of the table storing combinations.
*
* @param target The target string to construct.
* @param wordBank An iterable collection of substrings that can be used to construct the target.
* @return A list of lists, where each inner list represents one possible
* way of constructing the target string using the given word bank.
*/
public static List<List<String>> allConstruct(String target, Iterable<String> wordBank) {
List<List<List<String>>> table = new ArrayList<>(target.length() + 1);
for (int i = 0; i <= target.length(); i++) {
table.add(new ArrayList<>());
}
table.get(0).add(new ArrayList<>());
for (int i = 0; i <= target.length(); i++) {
if (!table.get(i).isEmpty()) {
for (String word : wordBank) {
if (i + word.length() <= target.length() && target.substring(i, i + word.length()).equals(word)) {
List<List<String>> newCombinations = new ArrayList<>();
for (List<String> combination : table.get(i)) {
List<String> newCombination = new ArrayList<>(combination);
newCombination.add(word);
newCombinations.add(newCombination);
}
table.get(i + word.length()).addAll(newCombinations);
}
}
}
}
return table.get(target.length());
}
}