Skip to content

Latest commit

 

History

History
89 lines (78 loc) · 2.44 KB

720.md

File metadata and controls

89 lines (78 loc) · 2.44 KB
  1. Longest Word in Dictionary
Given a list of strings words representing an English Dictionary, find the longest word in words that can be built one character at a time by other words in words. If there is more than one possible answer, return the longest word with the smallest lexicographical order.

If there is no answer, return the empty string.
Example 1:
Input: 
words = ["w","wo","wor","worl", "world"]
Output: "world"
Explanation: 
The word "world" can be built one character at a time by "w", "wo", "wor", and "worl".
Example 2:
Input: 
words = ["a", "banana", "app", "appl", "ap", "apply", "apple"]
Output: "apple"
Explanation: 
Both "apply" and "apple" can be built from other words in the dictionary. However, "apple" is lexicographically smaller than "apply".
Note:

All the strings in the input will only contain lowercase letters.
The length of words will be in the range [1, 1000].
The length of words[i] will be in the range [1, 30].

my thoughts:

1. sort the arr -> iterate the arr build a dict {valid_str, length} -> put all valid_str with max length to an arr -> sort the arr, return first string

my solution:

**********68ms
class Solution(object):
    def longestWord(self, words):
        """
        :type words: List[str]
        :rtype: str
        """
        words.sort()
                
        l = len(words)
        d = {}
        i = 0
        while i<l:
            if len(words[i]) == 1:
                d[words[i]] = 1
            if words[i][:-1] in d:
                d[words[i]] = len(words[i])
            i += 1
        max_l = max(d.values())
        res = []
        for s in d:
            if d[s] == max_l:
                res.append(s)
        res.sort()
        return res[0]

my comments:

from other ppl's solution:

1. just brutal force to avoid sorting, 45ms:
	
class Solution(object):
    def longestWord(self, words):
        """
        :type words: List[str]
        :rtype: str
        """
        #brute force using hashset and pruning. 
        words_set = set(words)      #change the words into set
        best = ''
        for i in words_set:
            if len(i) < len(best) or (len(i) == len(best) and i >= best):       #pruning
                continue
            prefix = ''
            for j in range(len(i) - 1):
                prefix += i[j]
                if prefix not in words_set:
                    break
why the following 'else'??
			else:
                best = i
        return best