IBM OA 面试真题解析:Filter Words by Letters 字符筛选

17次阅读
没有评论

Implement the function filter_words(words, letters) which takes as input:

  • a list of strings words, with the words to filter
  • a string letters, used to filter the words

Your filter_words function should return a list of strings from words that contain at least one letter in letters.

For example:

words = ['the', 'dog', 'got', 'a', 'bone']
letters = 'ae'

The returned list should preserve the original order of words.

这道题要求从单词列表中筛选出“至少包含一个指定字母”的单词,并保持原有顺序不变。最直接的做法是遍历每个单词,再检查它的字符是否与给定字母集合有交集;一旦某个字符命中,就把该单词加入结果并跳过剩余检查。为了提升查找效率,通常会先把 letters 转成集合,这样字符成员判断是 O(1) 级别。整体思路简单,核心在于用好“集合查找 + 遍历过滤”这一基础模式。

正文完
 0