557. Reverse Words in a String III(Solution || Leetcode easy || Java)
1 min readNov 24, 2022
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.
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.