In this post, we are going to solve the 557. Reverse Words in a String III problem of Leetcode. This problem 557. Reverse Words in a String III is a Leetcode medium level problem. Let’s see code, 557. Reverse Words in a String III.
Problem
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.
Now, let’s see the code of 557. Reverse Words in a String III – Leetcode Solution.
Reverse Words in a String III – Leetcode Solution
557. Reverse Words in a String III – Solution in Java
class Solution { public String reverseTheWord(String s){ String rev = ""; for(char ch : s.toCharArray()){ rev = ""+ch+rev; } return rev; } public String reverseWords(String s) { String ans = ""; for(String str : s.split(" ")){ ans += " "+ reverseTheWord(str) ; } return ans.trim(); } }
We can also solve this problem with another approach in Java, by using StringBuilder Class in Java.
557. Reverse Words in a String III – Solution in Java (using StringBuilder Class)
class Solution { public String reverseTheWord(String s){ StringBuilder rev = new StringBuilder(s); return rev.reverse().toString(); } public String reverseWords(String s) { String ans = ""; for(String str : s.split(" ")){ ans += " "+ reverseTheWord(str) ; } return ans.trim(); } }
557. Reverse Words in a String III – Solution in C++
class Solution { public: string reverseWords(string& s) { int i = 0; for (int j = 0; j < s.size(); ++j) { if (s[j] == ' ') { reverse(s.begin() + i, s.begin() + j); i = j + 1; } } reverse(s.begin() + i, s.end()); return s; } };
557. Reverse Words in a String III – Solution in Python
class Solution: def reverseWords(self, s: str) -> str: return ' '.join([w[::-1] for w in s.split(' ')])
Note: This problem 557. Reverse Words in a String III is generated by Leetcode but the solution is provided by CodingBroz. This tutorial is only for Educational and Learning purpose.