|
| 1 | +# 151. Reverse Words in a String - LeetCode Python/Java/C++/JS code |
| 2 | + |
| 3 | +Visit original link: [151. Reverse Words in a String - LeetCode Python/Java/C++/JS code](https://leetcode.blog/en/leetcode/151-reverse-words-in-a-string) for a better experience! |
| 4 | + |
| 5 | +LeetCode link: [151. Reverse Words in a String](https://leetcode.com/problems/reverse-words-in-a-string), difficulty: **Medium**. |
| 6 | + |
| 7 | +## LeetCode description of "151. Reverse Words in a String" |
| 8 | + |
| 9 | +Given an input string `s`, reverse the order of the **words**. |
| 10 | + |
| 11 | +A **word** is defined as a sequence of non-space characters. The **words** in `s` will be separated by at least one space. |
| 12 | + |
| 13 | +Return *a string of the words in reverse order concatenated by a single space*. |
| 14 | + |
| 15 | +**Note** that `s` 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. |
| 16 | + |
| 17 | +### [Example 1] |
| 18 | + |
| 19 | +**Input**: `s = "the sky is blue"` |
| 20 | + |
| 21 | +**Output**: `"blue is sky the"` |
| 22 | + |
| 23 | +### [Example 2] |
| 24 | + |
| 25 | +**Input**: `s = " hello world "` |
| 26 | + |
| 27 | +**Output**: `"world hello"` |
| 28 | + |
| 29 | +### [Example 3] |
| 30 | + |
| 31 | +**Input**: `"a good example"` |
| 32 | + |
| 33 | +**Output**: `"example good a"` |
| 34 | + |
| 35 | +### [Constraints] |
| 36 | + |
| 37 | +- `1 <= s.length <= 10^4` |
| 38 | +- `s` contains English letters (upper-case and lower-case), digits, and spaces `' '`. |
| 39 | +- There is **at least one** word in `s`. |
| 40 | + |
| 41 | +**Follow-up**: If the string data type is mutable in your language, can you solve it **in-place** with `O(1)` extra space? |
| 42 | + |
| 43 | + |
| 44 | + |
| 45 | +## Intuition |
| 46 | + |
| 47 | +1. Split the string into an array of words (need to remove empty strings) |
| 48 | +2. Reverse the order of the words |
| 49 | +3. Join the words with a single space |
| 50 | + |
| 51 | +## Step by Step Solutions |
| 52 | + |
| 53 | +1. Split the string using `split(' ')` |
| 54 | +2. Remove empty strings |
| 55 | +3. Reverse the word array using `reverse` |
| 56 | +4. Merge into the final string using `join(' ')` |
| 57 | + |
| 58 | +## Complexity |
| 59 | + |
| 60 | +- Time complexity: `O(N)`. |
| 61 | +- Space complexity: `O(N)`. |
| 62 | + |
| 63 | +## Python |
| 64 | + |
| 65 | +```python |
| 66 | +class Solution: |
| 67 | + def reverseWords(self, s: str) -> str: |
| 68 | + words = [word for word in s.split(' ') if word] |
| 69 | + return ' '.join(words[::-1]) |
| 70 | +``` |
| 71 | + |
| 72 | +## Java |
| 73 | + |
| 74 | +```java |
| 75 | +class Solution { |
| 76 | + public String reverseWords(String s) { |
| 77 | + var wordList = new ArrayList<String>(); |
| 78 | + var words = s.split(" "); |
| 79 | + |
| 80 | + for (var word : words) { |
| 81 | + if (!word.isEmpty()) { |
| 82 | + wordList.add(word); |
| 83 | + } |
| 84 | + } |
| 85 | + |
| 86 | + int left = 0; |
| 87 | + int right = wordList.size() - 1; |
| 88 | + while (left < right) { |
| 89 | + Collections.swap(wordList, left, right); |
| 90 | + left++; |
| 91 | + right--; |
| 92 | + } |
| 93 | + |
| 94 | + return String.join(" ", wordList); |
| 95 | + } |
| 96 | +} |
| 97 | +``` |
| 98 | + |
| 99 | +## C++ |
| 100 | + |
| 101 | +```cpp |
| 102 | +class Solution { |
| 103 | +public: |
| 104 | + string reverseWords(string s) { |
| 105 | + istringstream iss(s); |
| 106 | + string word; |
| 107 | + vector<string> word_list; |
| 108 | + |
| 109 | + // 1. Extract words from the string. |
| 110 | + // The istringstream >> operator automatically handles |
| 111 | + // multiple spaces between words and leading/trailing spaces. |
| 112 | + while (iss >> word) { |
| 113 | + word_list.push_back(word); |
| 114 | + } |
| 115 | + |
| 116 | + reverse(word_list.begin(), word_list.end()); |
| 117 | + |
| 118 | + // 2. Join the words with a single space. |
| 119 | + string result = ""; |
| 120 | + result = word_list[0]; |
| 121 | + for (auto i = 1; i < word_list.size(); ++i) { |
| 122 | + result += " "; |
| 123 | + result += word_list[i]; |
| 124 | + } |
| 125 | + |
| 126 | + return result; |
| 127 | + } |
| 128 | +}; |
| 129 | + |
| 130 | +``` |
| 131 | +
|
| 132 | +## JavaScript |
| 133 | +
|
| 134 | +```javascript |
| 135 | +var reverseWords = function(s) { |
| 136 | + const words = s.split(' ').filter((word) => word !== ''); |
| 137 | + return words.reverse().join(' '); |
| 138 | +}; |
| 139 | +``` |
| 140 | + |
| 141 | +## Go |
| 142 | + |
| 143 | +```go |
| 144 | +func reverseWords(s string) string { |
| 145 | + words := strings.Fields(s) // Fields splits on whitespace and ignores multiple spaces |
| 146 | + |
| 147 | + // Reverse the words |
| 148 | + for i, j := 0, len(words) - 1; i < j; { |
| 149 | + words[i], words[j] = words[j], words[i] |
| 150 | + i += 1 |
| 151 | + j -= 1 |
| 152 | + } |
| 153 | + |
| 154 | + return strings.Join(words, " ") |
| 155 | +} |
| 156 | +``` |
| 157 | + |
| 158 | +## C# |
| 159 | + |
| 160 | +```csharp |
| 161 | +public class Solution { |
| 162 | + public string ReverseWords(string s) { |
| 163 | + // Split into words, remove empty entries, reverse |
| 164 | + var words = s.Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries).Reverse(); |
| 165 | + return string.Join(" ", words); |
| 166 | + } |
| 167 | +} |
| 168 | +``` |
| 169 | + |
| 170 | +## Ruby |
| 171 | + |
| 172 | +```ruby |
| 173 | +def reverse_words(s) |
| 174 | + s.split(' ').reject(&:empty?).reverse.join(' ') |
| 175 | +end |
| 176 | +``` |
| 177 | + |
| 178 | +## Other languages |
| 179 | + |
| 180 | +```java |
| 181 | +// Welcome to create a PR to complete the code of this language, thanks! |
| 182 | +``` |
| 183 | + |
| 184 | +Dear LeetCoders! For a better LeetCode problem-solving experience, please visit website [LeetCode.blog](https://leetcode.blog): Dare to claim the best practices of LeetCode solutions! Will save you a lot of time! |
| 185 | + |
| 186 | +Original link: [151. Reverse Words in a String - LeetCode Python/Java/C++/JS code](https://leetcode.blog/en/leetcode/151-reverse-words-in-a-string). |
| 187 | + |
| 188 | +GitHub repository: [f*ck-leetcode](https://github.com/fuck-leetcode/fuck-leetcode). |
| 189 | + |
0 commit comments