public class Trie {
Trie[] children;
boolean isEnd;
public Trie() {
children = new Trie[26];
isEnd = false;
}
//插入
public void insert(String word) {
Trie node = this;
for (int i = 0; i < word.length(); i++) {
char ch = word.charAt(i);
int index = ch - 'a';
if (node.children[index] == null) {
node.children[index] = new Trie();
}
node = node.children[index];
}
node.isEnd = true;
}
//查询某个单词
public boolean search(String word) {
Trie node = searchPrefix(word);
return node != null && node.isEnd;
}
//查询前缀是否存在
public boolean startsWith(String prefix) {
return searchPrefix(prefix) != null;
}
//查询前缀,并返回前缀
private Trie searchPrefix(String prefix) {
Trie node = this;
for (int i = 0; i < prefix.length(); i++) {
char ch = prefix.charAt(i);
int index = ch - 'a';
if (node.children[index] == null) {
return null;
}
node = node.children[index];
}
return node;
}
}
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main{
static Trie trie=new Trie();
static int[] failMemo=new int[301];
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
List<String> list=new ArrayList<>();
list.add("leet");
list.add("code");
System.out.println(wordBreak("leetcode",list));
}
public static boolean wordBreak(String s, List<String> wordDict) {
for (String string:wordDict
) {
trie.insert(string);
}
return dfs(s,0);
}
public static boolean dfs(String s,int startPos){
if (failMemo[startPos] == 1) return false;
if (startPos == s.length()) return true;
Trie trie1;
trie1=trie;
for (int i = startPos; i < s.length(); i++) {
if (trie1.children[s.charAt(i)-'a']!=null)
{
trie1=trie1.children[s.charAt(i)-'a'];
if (trie1.isEnd&&dfs(s,i+1))
return true;
}
else break;
}
failMemo[startPos]=1;
return false;
}
}