-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprob7.java
More file actions
58 lines (52 loc) · 1.57 KB
/
prob7.java
File metadata and controls
58 lines (52 loc) · 1.57 KB
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
// We are given a dictionary of words and a large input string.
// We have to find out whether the input string can be completely segmented into the words of a given dictionary.
// The following two examples elaborate on the problem further.
import java.util.HashSet;
import java.util.Set;
public class prob7 {
public static void main(String[] args) {
System.out.println("String sementation");
testCase1();
testCase2();
}
private static void testCase1(){
Set<String> dict = new HashSet<String>();
String s = new String();
s = "applepie";
dict.add("pie");
dict.add("pear");
dict.add("apple");
dict.add("peach");
System.out.println(segment(s, dict));
}
private static void testCase2(){
Set<String> dict = new HashSet<String>();
String s = new String();
s = "applepiee";
dict.add("pie");
dict.add("pear");
dict.add("apple");
dict.add("peach");
System.out.println(segment(s, dict));
}
public static boolean segment(String str, Set<String> dict){
if (dict.contains(str))
return true;
return recSegment(str, dict, 0);
}
private static boolean recSegment(String str, Set<String> dict, int start){
if (start == str.length())
return true;
int end = start + 1;
while(end < str.length()){
if (dict.contains(str.substring(start, end))){
// not end + 1, because substring does not include the char at index end
if (recSegment(str, dict, end)){
return true;
}
}
end++;
}
return dict.contains(str.substring(start, end));
}
}