Sitemap

Leetcode Daily | 22–09–22 | Reverse Words in a String III

2 min readSep 22, 2022

Here is today’s Leetcode question🙌

Level- Easy

Question

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"

Approach

So the question is quite simple. All you need to do is reverse each word in the sentence while preserving their order.

  • Use C++ stringstream class and getline function.
  • The getline function will run for n times, where n is the number of words in string separated by space.
  • We will reverse each of those words and add them to our answer.

C++ Code

class Solution {
public:
string reverseWords(string s) {
stringstream ss(s);
string t, ans;

while (getline(ss, t, ' ')) {
reverse(t.begin(), t.end());
ans += t + ' ';
}
// We will take substring of one less size as there will be space after last word which is not required.
return ans.substr(0, ans.size() - 1);
}
};

Java Code

Press enter or click to view image in full size

Python Code

class Solution:
def reverseWords(self, s: str) -> str:
return ' '.join(word[::-1] for word in s.split())

Output

Press enter or click to view image in full size
Press enter or click to view image in full size

That’s it for today’s question. Let me know if you need anything else to be there in this blog. Thank you💕

--

--

No responses yet