LeetCode524:通过删除字母匹配到字典里最长单词(python)
2022/1/25 22:06:04
本文主要是介绍LeetCode524:通过删除字母匹配到字典里最长单词(python),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
题解:
s 中每个字符和 dictionary 中每个 字符串 进行比较,记录最长的那一个,且字典序是最小的。
先排序,解决最长字符串的同时字典序最小的问题
后比较,两个指针,分别指向 s 和 dictionary 中的字符串t,挨个比较。
当字符串t的指针长度跟字符串t本身长度一致,就说明 s 删除一些子串可以变成字符串t
class Solution: def findLongestWord(self, s: str, dictionary: List[str]) -> str: #先将dictionary进行排序,由长到短,然后再按字母小的在前 sorted_dictionary = sorted(dictionary,key = lambda x:[-len(x),x]) for t in sorted_dictionary: i=0 j = 0 while i <len(t) and j<len(s): if t[i]==s[j]: i += 1 j += 1 if i == len(t): return t return ''
这篇关于LeetCode524:通过删除字母匹配到字典里最长单词(python)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-08有遇到过吗?同样的规则 Excel 中 比Python 结果大
- 2024-03-30开始python成长之路
- 2024-03-29python optparse
- 2024-03-29python map 函数
- 2024-03-20invalid format specifier python
- 2024-03-18pool.map python
- 2024-03-18threads in python
- 2024-03-14python Ai 应用开发基础训练,字符串,字典,文件
- 2024-03-13id3 algorithm python
- 2024-03-13sum array elements python