-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_142wordBreak.java
More file actions
54 lines (54 loc) · 1.55 KB
/
_142wordBreak.java
File metadata and controls
54 lines (54 loc) · 1.55 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
public class _142wordBreak {
static class Node{
Node children[]= new Node[26];
boolean eow = false;
Node(){
for(int i = 0;i<26;i++){
children[i]=null;
}
}
}
public static Node root = new Node();
public static void insert(String word){
Node curr = root;
for(int level=0;level<word.length();level++){
int idx = word.charAt(level)-'a';
if(curr.children[idx]==null){
curr.children[idx]=new Node();
}
curr=curr.children[idx];
}
curr.eow=true;
}
public static boolean search(String key){
Node curr = root;
for(int level=0;level<key.length();level++){
int idx = key.charAt(level)-'a';
if(curr.children[idx]==null){
return false;
}
curr=curr.children[idx];
}
return curr.eow==true;
}
public static boolean wordBreak(String key){
if(key.length() == 0){
return true;
}
for(int i=1;i<=key.length();i++){
if(search(key.substring(0,i))&&
wordBreak(key.substring(i))){
return true;
}
}
return false;
}
public static void main(String[] args) {
String arr[] = {"i", "like", "sam", "samsung", "mobile", "ice"};
for(int i = 0;i<arr.length;i++){
insert(arr[i]);
}
String key="ilikesamsung";
System.out.println(wordBreak(key));
}
}