{"id":819,"date":"2017-11-16T20:41:55","date_gmt":"2017-11-17T04:41:55","guid":{"rendered":"http:\/\/zxi.mytechroad.com\/blog\/?p=819"},"modified":"2018-04-19T08:32:43","modified_gmt":"2018-04-19T15:32:43","slug":"leetcode-720-longest-word-in-dictionary","status":"publish","type":"post","link":"https:\/\/zxi.mytechroad.com\/blog\/string\/leetcode-720-longest-word-in-dictionary\/","title":{"rendered":"\u82b1\u82b1\u9171 LeetCode 720. Longest Word in Dictionary"},"content":{"rendered":"<p><iframe loading=\"lazy\" title=\"\u82b1\u82b1\u9171 LeetCode 720. Longest Word in Dictionary  - \u5237\u9898\u627e\u5de5\u4f5c EP109\" width=\"500\" height=\"375\" src=\"https:\/\/www.youtube.com\/embed\/TqrZg4wYP1U?feature=oembed\" frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share\" referrerpolicy=\"strict-origin-when-cross-origin\" allowfullscreen><\/iframe><\/p>\n<p>Given a list of strings\u00a0<code>words<\/code>\u00a0representing an English Dictionary, find the longest word in\u00a0<code>words<\/code>\u00a0that can be built one character at a time by other words in\u00a0<code>words<\/code>. If there is more than one possible answer, return the longest word with the smallest lexicographical order.<\/p>\n<p>If there is no answer, return the empty string.<\/p>\n<p><b>Example 1:<\/b><\/p>\n<pre class=\"\">Input: \r\nwords = [\"w\",\"wo\",\"wor\",\"worl\", \"world\"]\r\nOutput: \"world\"\r\nExplanation: \r\nThe word \"world\" can be built one character at a time by \"w\", \"wo\", \"wor\", and \"worl\".\r\n<\/pre>\n<p><b>Example 2:<\/b><\/p>\n<pre class=\"\">Input: \r\nwords = [\"a\", \"banana\", \"app\", \"appl\", \"ap\", \"apply\", \"apple\"]\r\nOutput: \"apple\"\r\nExplanation: \r\nBoth \"apply\" and \"apple\" can be built from other words in the dictionary. \r\nHowever, \"apple\" is lexicographically smaller than \"apply\".\r\n<\/pre>\n<p><b>Note:<\/b><\/p>\n<p>&nbsp;<\/p>\n<ul>\n<li>All the strings in the input will only contain lowercase letters.<\/li>\n<li>The length of\u00a0<code>words<\/code>\u00a0will be in the range\u00a0<code>[1, 1000]<\/code>.<\/li>\n<li>The length of\u00a0<code>words[i]<\/code>\u00a0will be in the range\u00a0<code>[1, 30]<\/code>.<\/li>\n<\/ul>\n<p><strong>Idea:<\/strong><\/p>\n<p>Brute force<\/p>\n<p>Trie<\/p>\n<p><a href=\"http:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/11\/720-ep109.png\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-828\" src=\"http:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/11\/720-ep109.png\" alt=\"\" width=\"960\" height=\"540\" srcset=\"https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/11\/720-ep109.png 960w, https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/11\/720-ep109-300x169.png 300w, https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/11\/720-ep109-768x432.png 768w, https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/11\/720-ep109-624x351.png 624w\" sizes=\"auto, (max-width: 960px) 100vw, 960px\" \/><\/a><\/p>\n<p><a href=\"http:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/11\/720-ep109-1.png\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-827\" src=\"http:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/11\/720-ep109-1.png\" alt=\"\" width=\"960\" height=\"540\" srcset=\"https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/11\/720-ep109-1.png 960w, https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/11\/720-ep109-1-300x169.png 300w, https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/11\/720-ep109-1-768x432.png 768w, https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/11\/720-ep109-1-624x351.png 624w\" sizes=\"auto, (max-width: 960px) 100vw, 960px\" \/><\/a><\/p>\n<p><strong>Solution:<\/strong><\/p>\n<p>C++<\/p>\n<pre class=\"lang:c++ decode:true \">\/\/ Author: Huahua\r\n\/\/ Runtime: 39 ms (better than 97.85%)\r\nclass Solution {\r\npublic:\r\n    string longestWord(vector&lt;string&gt;&amp; words) {\r\n        string best;        \r\n        unordered_set&lt;string&gt; dict(words.begin(), words.end());\r\n        \r\n        for (const string&amp; word : words) {\r\n            if (word.length() &lt; best.length() \r\n             || (word.length() == best.length() &amp;&amp; word &gt; best)) \r\n                continue;\r\n            string prefix;\r\n            bool valid = true;\r\n            for (int i = 0; i &lt; word.length() - 1 &amp;&amp; valid; ++i) {\r\n                prefix += word[i];\r\n                if (!dict.count(prefix)) valid = false;\r\n            }\r\n            if (valid) best = word;\r\n        }\r\n        \r\n        return best;\r\n    }\r\n};<\/pre>\n<p>&nbsp;<\/p>\n<pre class=\"lang:default decode:true \">\/\/ Author: Huahua\r\n\/\/ Runtime: 46 ms\r\nclass Solution {\r\npublic:\r\n    string longestWord(vector&lt;string&gt;&amp; words) {\r\n        \/\/ Sort by length DESC, if there is a tie, sort by lexcial order.\r\n        std::sort(words.begin(), words.end(), \r\n                  [](const string&amp; w1, const string&amp; w2){\r\n                    if (w1.length() != w2.length()) \r\n                        return w1.length() &gt; w2.length();\r\n                    return w1 &lt; w2;\r\n                  });\r\n        \r\n        unordered_set&lt;string&gt; dict(words.begin(), words.end());\r\n        \r\n        for (const string&amp; word : words) {\r\n            string prefix;\r\n            bool valid = true;\r\n            for (int i = 0; i &lt; word.length() - 1 &amp;&amp; valid; ++i) {\r\n                prefix += word[i];\r\n                if (!dict.count(prefix)) valid = false;\r\n            }\r\n            if (valid) return word;\r\n        }\r\n        \r\n        return \"\";\r\n    }\r\n};<\/pre>\n<p>&nbsp;<\/p>\n<p>Trie + Sorting<\/p>\n<pre class=\"lang:c++ decode:true \">\/\/ Author: Huahua\r\n\/\/ Runtime: 49 ms\r\nclass Trie {\r\npublic:\r\n    Trie(): root_(new TrieNode()) {}\r\n    \r\n    void insert(const string&amp; word) {\r\n        TrieNode* p = root_.get();\r\n        for (const char c : word) {\r\n            if (!p-&gt;children[c - 'a'])\r\n                p-&gt;children[c - 'a'] = new TrieNode();\r\n            p = p-&gt;children[c - 'a'];\r\n        }\r\n        p-&gt;is_word = true;\r\n    }\r\n    \r\n    bool hasAllPrefixes(const string&amp; word) {\r\n        const TrieNode* p = root_.get();\r\n        for (const char c : word) {\r\n            if (!p-&gt;children[c - 'a']) return false;\r\n            p = p-&gt;children[c - 'a'];\r\n            if (!p-&gt;is_word) return false;\r\n        }\r\n        return true;\r\n    }    \r\nprivate:\r\n    struct TrieNode {\r\n        TrieNode():is_word(false), children(26, nullptr){}\r\n        \r\n        ~TrieNode() {\r\n            for (auto node : children)\r\n                delete node;\r\n        }\r\n        \r\n        bool is_word;\r\n        vector&lt;TrieNode*&gt; children;\r\n    };\r\n    \r\n    std::unique_ptr&lt;TrieNode&gt; root_;\r\n};\r\n\r\nclass Solution {\r\npublic:\r\n    string longestWord(vector&lt;string&gt;&amp; words) {\r\n        std::sort(words.begin(), words.end(), \r\n          [](const string&amp; w1, const string&amp; w2){\r\n            if (w1.length() != w2.length()) \r\n                return w1.length() &gt; w2.length();\r\n            return w1 &lt; w2;\r\n          });\r\n            \r\n        Trie trie;\r\n        for (const string&amp; word : words)\r\n            trie.insert(word);\r\n                \r\n        for (const string&amp; word : words)\r\n            if (trie.hasAllPrefixes(word)) return word;  \r\n        \r\n        return \"\";\r\n    }\r\n};<\/pre>\n<p>&nbsp;<\/p>\n<p>Trie + No sorting<\/p>\n<pre class=\"lang:default decode:true\">\/\/ Author: Huahua\r\n\/\/ Runtime: 56 ms\r\nclass Trie {\r\npublic:\r\n    Trie(): root_(new TrieNode()) {}\r\n    \r\n    void insert(const string&amp; word) {\r\n        TrieNode* p = root_.get();\r\n        for (const char c : word) {\r\n            if (!p-&gt;children[c - 'a'])\r\n                p-&gt;children[c - 'a'] = new TrieNode();\r\n            p = p-&gt;children[c - 'a'];\r\n        }\r\n        p-&gt;is_word = true;\r\n    }\r\n    \r\n    bool hasAllPrefixes(const string&amp; word) {\r\n        const TrieNode* p = root_.get();\r\n        for (const char c : word) {\r\n            if (!p-&gt;children[c - 'a']) return false;\r\n            p = p-&gt;children[c - 'a'];\r\n            if (!p-&gt;is_word) return false;\r\n        }\r\n        return true;\r\n    }    \r\nprivate:\r\n    struct TrieNode {\r\n        TrieNode():is_word(false), children(26, nullptr){}\r\n        \r\n        ~TrieNode() {\r\n            for (auto node : children)\r\n                delete node;\r\n        }\r\n        \r\n        bool is_word;\r\n        vector&lt;TrieNode*&gt; children;\r\n    };\r\n    \r\n    std::unique_ptr&lt;TrieNode&gt; root_;\r\n};\r\n\r\nclass Solution {\r\npublic:\r\n    string longestWord(vector&lt;string&gt;&amp; words) {\r\n        Trie trie;\r\n        for (const string&amp; word : words)\r\n            trie.insert(word);\r\n        \r\n        string best;\r\n        for (const string&amp; word : words) {\r\n            if (word.length() &lt; best.length() \r\n            || (word.length() == best.length() &amp;&amp; word &gt; best))\r\n                continue;\r\n            if (trie.hasAllPrefixes(word))\r\n                best = word;\r\n        }\r\n        \r\n        return best;\r\n    }\r\n};<\/pre>\n<p>&nbsp;<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Given a list of strings\u00a0words\u00a0representing an English Dictionary, find the longest word in\u00a0words\u00a0that can be built one character at a time by other words in\u00a0words.&#8230;<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[163,47],"tags":[97,96],"class_list":["post-819","post","type-post","status-publish","format-standard","hentry","category-easy","category-string","tag-prefix","tag-trie","entry","simple"],"_links":{"self":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts\/819","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/comments?post=819"}],"version-history":[{"count":10,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts\/819\/revisions"}],"predecessor-version":[{"id":2592,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts\/819\/revisions\/2592"}],"wp:attachment":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/media?parent=819"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/categories?post=819"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/tags?post=819"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}