-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWordBreakProblem.java
More file actions
47 lines (39 loc) · 1.46 KB
/
WordBreakProblem.java
File metadata and controls
47 lines (39 loc) · 1.46 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
package com.sai;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class WordBreakProblem {
private static final Set<String> dictionary = new HashSet<String>(Arrays.asList("IDeserve", "learning", "IDeservelearningplatform"));
public static boolean hasValidWords(String words) {
// Empty string
if(words == null || words.length() == 0) {
return true;
}
int n = words.length();
boolean[] validWords = new boolean[n];
for (int i = 0; i < n; i++) {
if (dictionary.contains(words.substring(0, i + 1))) {
validWords[i] = true;
}
if (validWords[i] == true && (i == n - 1))
return true;
if (validWords[i] == true) {
for (int j = i + 1; j < n; j++) {
if (dictionary.contains(words.substring(i + 1, j + 1))) {
validWords[j] = true;
}
if (j == n - 1 && validWords[j] == true) {
return true;
}
}
}
}
return false;
}
public static void main(String[] args) {
if (hasValidWords("IDeservelearningplatform"))
System.out.println("String has valid words");
else
System.out.println("String doesn't have any valid words");
}
}