304 North Cardinal St.
Dorchester Center, MA 02124

# Reverse Words in a String III LeetCode Solution

## Problem – Reverse Words in a String III

Given a string `s`, reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.

Example 1:

``````Input: s = "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"``````

Example 2:

``````Input: s = "God Ding"
Output: "doG gniD"``````

Constraints:

• `1 <= s.length <= 5 * 104`
• `s` contains printable ASCII characters.
• `s` does not contain any leading or trailing spaces.
• There is at least one word in `s`.
• All the words in `s` are separated by a single space.

### Reverse Words in a String III LeetCode Solution in Python

``````def reverseWords(self, s):
return ' '.join(s.split()[::-1])[::-1]
``````

### Reverse Words in a String III LeetCode Solution in C++

``````class Solution {
public:
string reverseWords(string s) {
for (int i = 0; i < s.length(); i++) {
if (s[i] != ' ') {   // when i is a non-space
int j = i;
for (; j < s.length() && s[j] != ' '; j++) { } // move j to the next space
reverse(s.begin() + i, s.begin() + j);
i = j - 1;
}
}

return s;
}
};
``````

### Reverse Words in a String III LeetCode Solution in Java

``````public class Solution {
public String reverseWords(String s) {
char[] ca = s.toCharArray();
for (int i = 0; i < ca.length; i++) {
if (ca[i] != ' ') {   // when i is a non-space
int j = i;
while (j + 1 < ca.length && ca[j + 1] != ' ') { j++; } // move j to the end of the word
reverse(ca, i, j);
i = j;
}
}
return new String(ca);
}

private void reverse(char[] ca, int i, int j) {
for (; i < j; i++, j--) {
char tmp = ca[i];
ca[i] = ca[j];
ca[j] = tmp;
}
}
}
``````
##### Reverse Words in a String III LeetCode Solution Review:

In our experience, we suggest you solve this Reverse Words in a String III LeetCode Solution and gain some new skills from Professionals completely free and we assure you will be worth it.

If you are stuck anywhere between any coding problem, just visit Queslers to get the Reverse Words in a String III LeetCode Solution

Find on LeetCode

##### Conclusion:

I hope this Reverse Words in a String III LeetCode Solution would be useful for you to learn something new from this problem. If it helped you then don’t forget to bookmark our site for more Coding Solutions.

This Problem is intended for audiences of all experiences who are interested in learning about Data Science in a business context; there are no prerequisites.

Keep Learning!

More Coding Solutions >>

LeetCode Solutions

Hacker Rank Solutions

CodeChef Solutions