Advertisement
goodwish

1190. Longest Word in Dictionary through Deleting

Oct 28th, 2019
172
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.35 KB | None | 0 0
  1. way 1: O(m*n) time.
  2. 字典按照要求排序, 长度 + 字典序.
  3. 对应每一个字典单词, 看看它是不是 s 的一个子序列.
  4.  
  5. Note. Python 字符串 iterator 用法. it = iter(s)
  6. for c1 in it:
  7. if c not in it:
  8. 省却了 next(it) 异常处理.
  9.  
  10. class Solution:
  11.     def findLongestWord(self, s, d):
  12.         # init
  13.         for x in sorted(d, key=lambda x: (-len(x), x)):
  14.             it = iter(s)
  15.             is_lcs = False
  16.             for c in x:
  17.                 is_lcs = False
  18.                 for c1 in it:
  19.                     if c == c1:
  20.                         is_lcs = True
  21.                         break
  22.             if is_lcs:
  23.                 return x
  24.         return ''
  25.  
  26. class Solution:
  27.     def findLongestWord(self, s, d):
  28.         # init
  29.         for x in sorted(d, key=lambda x: (-len(x), x)):
  30.             it = iter(s)
  31.             is_lcs = True
  32.             for c in x:
  33.                 if c not in it:
  34.                     is_lcs = False
  35.                     continue
  36.             if is_lcs:
  37.                 return x
  38.         return ''
  39.  
  40. def findLongestWord(self, s, d):
  41.     for x in sorted(d, key=lambda x: (-len(x), x)):
  42.         it = iter(s)
  43.         if all(c in it for c in x):
  44.             return x
  45.     return ''
  46.  
  47. s = "barfoofoobarthefoobarman"
  48. d = ["xbar","foo","the"]
  49.  
  50. o = Solution()
  51. ans = o.findLongestWord(s, d)
  52. print(ans)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement