class WordFilter {
static class Node {
Node[] node = new Node[26];// 用26位来存储字母
List<Integer> indices = new ArrayList<>();// 每个节点对应的下标集合
}
private final Node root;// 前缀树
private final Node tail;// 后缀树
public WordFilter(String[] words) {
root = new Node();
tail = new Node();
for (int i = 0; i < words.length; i++) {
Node prefix = root;// 临时节点prefix,用于root
Node suffix = tail;// 临时节点suffix,用于tail
char[] arr = words[i].toCharArray();
for (int j = 0; j < arr.length; j++) {
int idx = arr[j] - 'a';
if (prefix.node[idx] == null) {
prefix.node[idx] = new Node();
}
prefix = prefix.node[idx];
prefix.indices.add(i);
idx = arr[arr.length - j - 1] - 'a';
if (suffix.node[idx] == null) {
suffix.node[idx] = new Node();
}
suffix = suffix.node[idx];
suffix.indices.add(i);
}
}
}
public int f(String pref, String suff) {
// node是一个临时节点,这里用前缀树root赋值给它
Node node = root;
// 从前往后遍历pref: a
for (char c : pref.toCharArray()) {
node = node.node[c - 'a'];
if (node == null) {
return -1;
}
}
// 得到的node为a节点==>对应indices[0,1]
List<Integer> prefixIndices = node.indices;// 得到前缀下标集合[0,1]
// --------分割线,上面计算前缀下标,下面计算后缀下标----------
// node是一个临时节点,这里用后缀树tail赋值给它
node = tail;
char[] arr = suff.toCharArray();
// 从后往前遍历suff: e
for (int i = arr.length - 1; i >= 0; i--) {
node = node.node[arr[i] - 'a'];
if (node == null) {
return -1;
}
}
// 得到的node为e节点==>对应indices[0]
List<Integer> suffixIndices = node.indices;// 得到后缀下标集合[0]
// 下面的计算用于取prefixIndices和suffixIndices交集的最大值
int i = prefixIndices.size() - 1;
int j = suffixIndices.size() - 1;
while (i >= 0 && j >= 0) {
int a = prefixIndices.get(i);
int b = suffixIndices.get(j);
if (a == b) {
return a;
} else if (a > b) {
i--;
} else {
j--;
}
}
return -1;
}
}