|
| 1 | +# [1858. Longest Word With All Prefixes](https://leetcode.com/problems/longest-word-with-all-prefixes) |
| 2 | + |
| 3 | +[中文文档](/solution/1800-1899/1858.Longest%20Word%20With%20All%20Prefixes/README.md) |
| 4 | + |
| 5 | +## Description |
| 6 | + |
| 7 | +<p>Given an array of strings <code>words</code>, find the <strong>longest</strong> string in <code>words</code> such that <strong>every prefix</strong> of it is also in <code>words</code>.</p> |
| 8 | + |
| 9 | +<ul> |
| 10 | + <li>For example, let <code>words = ["a", "app", "ap"]</code>. The string <code>"app"</code> has prefixes <code>"ap"</code> and <code>"a"</code>, all of which are in <code>words</code>.</li> |
| 11 | +</ul> |
| 12 | + |
| 13 | +<p>Return <em>the string described above. If there is more than one string with the same length, return the <strong>lexicographically smallest</strong> one, and if no string exists, return </em><code>""</code>.</p> |
| 14 | + |
| 15 | +<p> </p> |
| 16 | + |
| 17 | +<p><strong>Example 1:</strong></p> |
| 18 | + |
| 19 | +<pre> |
| 20 | + |
| 21 | +<strong>Input:</strong> words = ["k","ki","kir","kira", "kiran"] |
| 22 | + |
| 23 | +<strong>Output:</strong> "kiran" |
| 24 | + |
| 25 | +<strong>Explanation:</strong> "kiran" has prefixes "kira", "kir", "ki", and "k", and all of them appear in words. |
| 26 | + |
| 27 | +</pre> |
| 28 | + |
| 29 | +<p><strong>Example 2:</strong></p> |
| 30 | + |
| 31 | +<pre> |
| 32 | + |
| 33 | +<strong>Input:</strong> words = ["a", "banana", "app", "appl", "ap", "apply", "apple"] |
| 34 | + |
| 35 | +<strong>Output:</strong> "apple" |
| 36 | + |
| 37 | +<strong>Explanation:</strong> Both "apple" and "apply" have all their prefixes in words. |
| 38 | + |
| 39 | +However, "apple" is lexicographically smaller, so we return that. |
| 40 | + |
| 41 | +</pre> |
| 42 | + |
| 43 | +<p><strong>Example 3:</strong></p> |
| 44 | + |
| 45 | +<pre> |
| 46 | + |
| 47 | +<strong>Input:</strong> words = ["abc", "bc", "ab", "qwe"] |
| 48 | + |
| 49 | +<strong>Output:</strong> "" |
| 50 | + |
| 51 | +</pre> |
| 52 | + |
| 53 | +<p> </p> |
| 54 | + |
| 55 | +<p><strong>Constraints:</strong></p> |
| 56 | + |
| 57 | +<ul> |
| 58 | + <li><code>1 <= words.length <= 10<sup>5</sup></code></li> |
| 59 | + <li><code>1 <= words[i].length <= 10<sup>5</sup></code></li> |
| 60 | + <li><code>1 <= sum(words[i].length) <= 10<sup>5</sup></code></li> |
| 61 | +</ul> |
| 62 | + |
| 63 | +## Solutions |
| 64 | + |
| 65 | +<!-- tabs:start --> |
| 66 | + |
| 67 | +### **Python3** |
| 68 | + |
| 69 | +```python |
| 70 | + |
| 71 | +``` |
| 72 | + |
| 73 | +### **Java** |
| 74 | + |
| 75 | +```java |
| 76 | + |
| 77 | +``` |
| 78 | + |
| 79 | +### **...** |
| 80 | + |
| 81 | +``` |
| 82 | +
|
| 83 | +``` |
| 84 | + |
| 85 | +<!-- tabs:end --> |
0 commit comments