Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 8 additions & 9 deletions hutool-dfa/src/main/java/cn/hutool/dfa/WordTree.java
Original file line number Diff line number Diff line change
Expand Up @@ -102,23 +102,22 @@ public WordTree addWord(String word) {
WordTree parent = null;
WordTree current = this;
WordTree child;
char currentChar = 0;
Character lastAcceptedChar = null;

final int length = word.length();
for (int i = 0; i < length; i++) {
currentChar = word.charAt(i);
char currentChar = word.charAt(i);
if (charFilter.accept(currentChar)) {//只处理合法字符
child = current.get(currentChar);
if (child == null) {
//无子类,新建一个子节点后存放下一个字符
child = new WordTree();
current.put(currentChar, child);
}
child = current.computeIfAbsent(currentChar, c -> new WordTree());
parent = current;
current = child;
lastAcceptedChar = currentChar;
}
}
// 仅当存在父节点且存在非停顿词时,才设置词尾标记
// 当 null != parent 条件成立时,lastAcceptedChar != null 必然成立,故也可以省去
if (null != parent) {
parent.setEnd(currentChar);
parent.setEnd(lastAcceptedChar);
}
return this;
}
Expand Down
28 changes: 28 additions & 0 deletions hutool-dfa/src/test/java/cn/hutool/dfa/DfaTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,34 @@ public void stopWordTest() {
assertEquals(all, CollUtil.newArrayList("t-io"));
}

/**
* Github Issue #4091
* 测试当关键词以停顿词结尾时,其合法前缀是否能被正确匹配
*/
@Test
public void addWordWithTrailingFilteredCharTest() {
WordTree tree = new WordTree();
tree.addWord("hello("); // 以停顿词 '(' 结尾

List<String> matches = tree.matchAll("hello", -1);
assertEquals(1, matches.size());
assertEquals("hello", matches.get(0));
}

/**
* Github Issue #4091
* 测试关键词中间包含停顿词的情况
*/
@Test
public void addWordWithMiddleFilteredCharTest() {
WordTree tree = new WordTree();
tree.addWord("he(llo"); // 中间 '(' 被过滤

List<String> matches = tree.matchAll("hello", -1);
assertEquals(1, matches.size());
assertEquals("hello", matches.get(0));
}

@Test
public void aTest(){
WordTree tree = new WordTree();
Expand Down