-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path139.word-break.java
65 lines (60 loc) · 1.69 KB
/
139.word-break.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
63
64
65
class Solution {
class TrieNode {
TrieNode[] child;
Boolean isEnd;
TrieNode(){
child = new TrieNode[26];
isEnd = false;
}
}
Trie tr;
Boolean[] hsm;
class Trie{
TrieNode root;
Trie(){
root = new TrieNode();
}
public void insert(String s){
if(s.length() == 0)
return;
TrieNode curr = root;
for(int i =0;i<s.length();i++){
int ind = s.charAt(i)-'a';
if(curr.child[ind] == null)
curr.child[ind] = new TrieNode();
curr = curr.child[ind];
}
curr.isEnd = true;
}
public boolean search(String s, int p){
// System.out.println(s);
if(p == s.length())
return true;
if(hsm[p] != null)
return hsm[p];
TrieNode curr = root;
boolean res = false;
for(int i =p;i<s.length();i++){
int ind = s.charAt(i)-'a';
if(curr.child[ind] == null)
return hsm[p] = res;
curr = curr.child[ind];
if(curr != null && curr.isEnd){
res = res || search(s, i+1);
// if(res)
// return res;
}
}
return hsm[p] = res ;
}
}
public boolean wordBreak(String s, List<String> wordDict) {
if(s.length() == 0 || wordDict.size() == 0)
return false;
hsm = new Boolean[s.length()+1];
tr = new Trie();
for(int i=0;i<wordDict.size();i++)
tr.insert(wordDict.get(i));
return tr.search(s, 0);
}
}