557. Reverse Words in a String III(Solution || Leetcode easy || Java)

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:

  • 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.

SOLUTION:

class Solution {
public String reverseWords(String s) {
//Store words of s as elements of an array
String[] temp = s.split(" ");

//Create a stringbuilder array to reverse the elements
StringBuilder[] sb = new StringBuilder[temp.length];


//Add elements from the string array to the stringbuilder array and
//also reverse them
for(int i = 0; i < temp.length; i++){
sb[i] = new StringBuilder(temp[i]);
sb[i] = sb[i].reverse();
}
//Create a stringbuilder or you can also make a string to add
//the reversed elements
StringBuilder ans = new StringBuilder();

for(int i = 0; i < temp.length; i++){
if(i < temp.length - 1){
ans.append(sb[i] + " ");
}else{
ans.append(sb[i]);
}
}



return ans.toString();
}
}

Thank you for reading. If you have any queries then, please let me know in the comment section. I will surely be responsive toward it.

--

--

Solutions to all your coding related problems at one point. DSA question on daily basis and much more.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Palakkgoyal

Solutions to all your coding related problems at one point. DSA question on daily basis and much more.