"""
通过删除字母匹配到字典里最长单词
desc: 给定字符串和字符串字典,找到字典中可以通过删除给定字符串的某些字符所形成的
最长字符串。如果有多个可能的结果,则返回具有最小字典顺序的最长单词。如果没有
可能的结果,则返回空字。
e.g.: 输入s="abpcplea", d=["ale", "apple", "monkey", "plea"], 输出apple。
"""
def find_word(s: str, d: list) -> str:
# lambda x: (-len(x), x) 排序首先按照字符串长度逆序排序,然后按照字典顺序排序
for i in sorted(d, key=lambda x: (-len(x), x)):
# 构造迭代器
it = iter(s)
if all(c in it for c in i):
"""
(c in it for c in i) - bool类型迭代器
如果字符串s的所有字母都在i中,i即为最长的单词
"""
return i
return ''
if __name__ == '__main__':
s = "abpcplea"
d = ["ale", "monke", "apple", "monkey", "plea"]
res = find_word(s, d)
print(res)