// 构建Trie树
export const buildTrie = (keywords) => {
  const root = { maxLength: 0 };
  let maxLength = 0;
  for (const word of keywords) {
    const normalizedWord = word.toLowerCase();
    maxLength = Math.max(maxLength, normalizedWord.length);
    let node = root;
    for (const char of normalizedWord) {
      if (!node[char]) node[char] = {};
      node = node[char];
    }
    node.isEnd = true;
    node.word = word; // 存储原始单词
  }
  root.maxLength = maxLength;
  return root;
};

export const findKeyword = (input, trie) => {
  const str = input.toLowerCase();
  const maxLen = trie.maxLength;
  const len = str.length;
  const results = [];

  for (let i = 0; i < len; i++) {
    let node = trie;
    for (let j = i; j < Math.min(i + maxLen, len); j++) {
      const char = str[j];
      node = node[char];
      if (!node) break;
      if (node.isEnd) results.push(node.word); // 添加找到的关键字到结果数组
    }
  }
  return results; // 返回所有找到的关键字
};
