forked from sPredictorX1708/Ultimate-Java-Resources
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWordBreakProblem.java
More file actions
60 lines (48 loc) · 1.65 KB
/
WordBreakProblem.java
File metadata and controls
60 lines (48 loc) · 1.65 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
59
60
import java.util.Set;
public class WordBreakProblem
{
// set to hold dictionary values
private static Set<String> dictionary = new HashSet<>();
public static void main(String []args)
{
// array of strings to be added in dictionary set.
String temp_dictionary[] = {"mobile","samsung","sam","sung",
"man","mango","icecream","and",
"go","i","like","ice","cream"};
// loop to add all strings in dictionary set
for (String temp :temp_dictionary)
{
dictionary.add(temp);
}
// sample input cases
System.out.println(wordBreak("ilikesamsung"));
System.out.println(wordBreak("iiiiiiii"));
System.out.println(wordBreak(""));
System.out.println(wordBreak("ilikelikeimangoiii"));
System.out.println(wordBreak("samsungandmango"));
System.out.println(wordBreak("samsungandmangok"));
}
// returns true if the word can be segmented into parts such
// that each part is contained in dictionary
public static boolean wordBreak(String word)
{
int size = word.length();
// base case
if (size == 0)
return true;
//else check for all words
for (int i = 1; i <= size; i++)
{
// Now we will first divide the word into two parts ,
// the prefix will have a length of i and check if it is
// present in dictionary ,if yes then we will check for
// suffix of length size-i recursively. if both prefix and
// suffix are present the word is found in dictionary.
if (dictionary.contains(word.substring(0,i)) &&
wordBreak(word.substring(i,size)))
return true;
}
// if all cases failed then return false
return false;
}
}