-
Notifications
You must be signed in to change notification settings - Fork 692
/
StringSegmentation.java
62 lines (49 loc) · 1.97 KB
/
StringSegmentation.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
62
package strings;
import java.util.HashSet;
import java.util.Set;
public class StringSegmentation {
/*
* Given a dictionary of words and an input string tell whether the input string can be completely
* segmented into dictionary words
* Eg: Input - Set<String> dict = [hello, hell, on, now], String s = "hellonow"
* Output - Can "hellonow" be segmented into Hello & now? - true or false
*
* Runtime Complexity - Polynomial, O(n2).
* Memory Complexity - Polynomial, O(n2). Memory Complexity is O(n2), because we create substring on each recursion
* call.
*
* We are using memorization - remembering the already solved substrings, so we don't go about solving them again.
* This will reduce the runtime of the algorithm to O(n2)
*
* */
public static boolean canBeSegmented(Set<String> firstDict,
Set<String> secondDict,
String s) {
for(int i=1; i<s.length(); i++) {
String first = s.substring(0, i);
if(firstDict.contains(first)) {
String second = s.substring(i);
if(second == null || second.length() == 0 || firstDict.contains(second)) {
return true;
}
if(!secondDict.contains(second)) {
if(!canBeSegmented(firstDict, secondDict, second)) {
return false;
}
secondDict.add(second);
}
}
}
return false;
}
public static void main(String[] args) {
Set<String> firstDict = new HashSet<>();
firstDict.add("apple");
firstDict.add("pear");
firstDict.add("pier");
firstDict.add("pie");
Set<String> secondDict = new HashSet<>();
String string = "pearpie";
System.out.println(canBeSegmented(firstDict,secondDict, string));
}
}