GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — leetcode/python/720_Longest_Word_in_Dictionary.py at master · qiyuangong/leetcode

Expand file tree

/

720_Longest_Word_in_Dictionary.py

Copy path
More file actions
More file actions

Latest commit

 

History

History
History
36 lines (34 loc) · 1.26 KB
/

720_Longest_Word_in_Dictionary.py

Copy path

File metadata and controls

36 lines (34 loc) · 1.26 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class Solution(object):
# def longestWord(self, words):
# words.sort()
# words_set, longest_word = set(['']), ''
# for word in words:
# if word[:-1] in words_set:
# words_set.add(word)
# if len(word) > len(longest_word):
# longest_word = word
# return longest_word
# def longestWord(self, words):
# ans = ""
# wordset = set(words)
# for word in words:
# if len(word) > len(ans) or len(word) == len(ans) and word < ans:
# if all(word[:k] in wordset for k in xrange(1, len(word))):
# ans = word
# return ans
def longestWord(self, words):
Trie = lambda: collections.defaultdict(Trie)
trie = Trie()
END = True
for i, word in enumerate(words):
reduce(dict.__getitem__, word, trie)[END] = i
stack = trie.values()
ans = ""
while stack:
cur = stack.pop()
if END in cur:
word = words[cur[END]]
if len(word) > len(ans) or len(word) == len(ans) and word < ans:
ans = word
stack.extend([cur[letter] for letter in cur if letter != END])
return ans
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.