中等
技术面试4 次浏览

编写一个Python函数,用于检测微博文本中是否包含敏感词,要求使用字典树(Trie树)实现。

微博安全工程师
编码能力敏感词检测

答题要点

答题时按照函数设计的步骤来进行。关键要点:1. 构建字典树,将敏感词插入到字典树中。2. 遍历微博文本,在字典树中查找是否存在敏感词。3. 对于匹配到的敏感词进行相应处理。示例代码思路:首先定义一个Trie树类,实现插入和查找方法。然后编写一个函数,将敏感词插入到Trie树中,再遍历微博文本进行查找。如果找到敏感词,可进行标记或替换等操作。例如:python class TrieNode: def __init__(self): self.children = {} self.is_end = False class Trie: def __init__(self): self.root = TrieNode() def insert(self, word): node = self.root for char in word: if char not in node.children: node.children[char] = TrieNode() node = node.children[char] node.is_end = True def search(self, text): node = self.root for char in text: if char not in node.children: return False node = node.children[char] return node.is_end def detect_sensitive_words(text, sensitive_words): trie = Trie() for word in sensitive_words: trie.insert(word) for i in range(len(text)): if trie.search(text[i:]): return True return False