|
| 1 | +<h2><a href="https://leetcode.com/problems/reverse-words-in-a-string/">151. Reverse Words in a String</a></h2><h3>Medium</h3><hr><div><p>Given an input string <code>s</code>, reverse the order of the <strong>words</strong>.</p> |
| 2 | + |
| 3 | +<p>A <strong>word</strong> is defined as a sequence of non-space characters. The <strong>words</strong> in <code>s</code> will be separated by at least one space.</p> |
| 4 | + |
| 5 | +<p>Return <em>a string of the words in reverse order concatenated by a single space.</em></p> |
| 6 | + |
| 7 | +<p><b>Note</b> that <code>s</code> may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces.</p> |
| 8 | + |
| 9 | +<p> </p> |
| 10 | +<p><strong class="example">Example 1:</strong></p> |
| 11 | + |
| 12 | +<pre><strong>Input:</strong> s = "the sky is blue" |
| 13 | +<strong>Output:</strong> "blue is sky the" |
| 14 | +</pre> |
| 15 | + |
| 16 | +<p><strong class="example">Example 2:</strong></p> |
| 17 | + |
| 18 | +<pre><strong>Input:</strong> s = " hello world " |
| 19 | +<strong>Output:</strong> "world hello" |
| 20 | +<strong>Explanation:</strong> Your reversed string should not contain leading or trailing spaces. |
| 21 | +</pre> |
| 22 | + |
| 23 | +<p><strong class="example">Example 3:</strong></p> |
| 24 | + |
| 25 | +<pre><strong>Input:</strong> s = "a good example" |
| 26 | +<strong>Output:</strong> "example good a" |
| 27 | +<strong>Explanation:</strong> You need to reduce multiple spaces between two words to a single space in the reversed string. |
| 28 | +</pre> |
| 29 | + |
| 30 | +<p> </p> |
| 31 | +<p><strong>Constraints:</strong></p> |
| 32 | + |
| 33 | +<ul> |
| 34 | + <li><code>1 <= s.length <= 10<sup>4</sup></code></li> |
| 35 | + <li><code>s</code> contains English letters (upper-case and lower-case), digits, and spaces <code>' '</code>.</li> |
| 36 | + <li>There is <strong>at least one</strong> word in <code>s</code>.</li> |
| 37 | +</ul> |
| 38 | + |
| 39 | +<p> </p> |
| 40 | +<p><b data-stringify-type="bold">Follow-up: </b>If the string data type is mutable in your language, can you solve it <b data-stringify-type="bold">in-place</b> with <code data-stringify-type="code">O(1)</code> extra space?</p> |
| 41 | +</div> |
0 commit comments