Reverse Words in the Given String
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
Given Input: s = “Let’s take LeetCode contest”
Expected Output: “s’teL ekat edoCteeL tsetnoc”
Steps to solve this problem
- Split the given string wherever the white space occurs
- Add all the split strings into one array
- Now, loop over all the strings of an array
- We need the string to be reversed, so I am going to stack which gives the elements in reverse order
- Add all the elements into the stack
- Now, remove all the elements of the stack and add them to a new string
- You got a reversed string
- Add this reversed string to the main string with a white space
- That’s it.
class Solution {
public String reverseWords(String s) {
//split the spring where ever white space occur
String arr[]=s.split(" ");
StringBuilder ans=new StringBuilder();
// loop through all the arr of string
for(int i=0;i<arr.length;i++){
Stack<Character>stack=new Stack<Character>();
//traverse all the characters of string
for(int j=0;j<arr[i].length();j++){
stack.push(arr[i].charAt(j));
}
StringBuilder sb=new StringBuilder();
while(!stack.isEmpty()){
sb.append(stack.pop());
}
// tracker for adding white spaces after adding each reversed string
if(i<arr.length-1){
ans.append(sb);
ans.append(" ");
}else{
ans.append(sb);
}
}
return ans.toString();
}
}
class Solution {
public String reverseWords(String s) {
//split the spring where ever white space occur
String arr[]=s.split(" ");
StringBuilder ans=new StringBuilder();
// loop through all the arr of string
for(int i=0;i<arr.length;i++){
Stack<Character>stack=new Stack<Character>();
//traverse all the characters of string
for(int j=0;j<arr[i].length();j++){
stack.push(arr[i].charAt(j));
}
StringBuilder sb=new StringBuilder();
while(!stack.isEmpty()){
sb.append(stack.pop());
}
// tracker for adding white spaces after adding each reversed string
if(i<arr.length-1){
ans.append(sb);
ans.append(" ");
}else{
ans.append(sb);
}
}
return ans.toString();
}
}
class Solution { public String reverseWords(String s) { //split the spring where ever white space occur String arr[]=s.split(" "); StringBuilder ans=new StringBuilder(); // loop through all the arr of string for(int i=0;i<arr.length;i++){ Stack<Character>stack=new Stack<Character>(); //traverse all the characters of string for(int j=0;j<arr[i].length();j++){ stack.push(arr[i].charAt(j)); } StringBuilder sb=new StringBuilder(); while(!stack.isEmpty()){ sb.append(stack.pop()); } // tracker for adding white spaces after adding each reversed string if(i<arr.length-1){ ans.append(sb); ans.append(" "); }else{ ans.append(sb); } } return ans.toString(); } }