题目
给你一个字符串 s 和一个字符串数组 dictionary 作为字典,找出并返回字典中最长的字符串,该字符串可以通过删除 s 中的某些字符得到。
如果答案不止一个,返回长度最长且字典序最小的字符串。如果答案不存在,则返回空字符串。
示例
示例1
输入:s = “abpcplea”, dictionary = [“ale”,“apple”,“monkey”,“plea”]
输出:“apple”
示例2
输入:s = “abpcplea”, dictionary = [“a”,“b”,“c”]
输出:“a”
关键思路
按顺序将字符串s中的每个字符与字典单词中的每个字符进行匹配,在此之前我们需要设置一个列表 index 用来维护每个单词已经被匹配到的下标。当循环结束后,根据 index 列表中的下标,选取字典中最长的字符串。
代码实现
class Solution(object):
def findLongestWord(self, s, dictionary):
"""
:type s: str
:type dictionary: List[str]
:rtype: str
"""
index = [ [0, w] for w in dictionary ] # to save corresponding index between s and d
for c in s:
for j in range(len(dictionary)): # current character is equal to c
if index[j][0] != len(dictionary[j]) and dictionary[j][index[j][0]] == c:
index[j][0] = index[j][0] + 1 # next charater
index.sort(key=lambda x:x[0], reverse=True)
if index[0][0] == 0:
return ""
for k in index:
if k[0] == len(k[1]):
return k[1]
if __name__ == "__main__":
s = input()
dictionary = input()
obj = Solution()
result = obj.findLongestWord(s, dictionary)
print(result)
运行结果
apple
a
实验心得
突然意识到写条件判断的时候,是依次按照if判断句中的先后顺序进行判断。例如,当条件判断句为if A and B时,先对A进行判断,如果A为False,那么程序就不会对B进行判断。
链接
https://leetcode-cn.com/problems/longest-word-in-dictionary-through-deleting