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.


Given Input: s = “Let’s take LeetCode contest”

Expected Output: “s’teL ekat edoCteeL tsetnoc”

Steps to solve this problem

  1. Split the given string wherever the white space occurs
  2. Add all the split strings into one array
  3. Now, loop over all the strings of an array
  4. We need the string to be reversed, so I am going to stack which gives the elements in reverse order
  5. Add all the elements into the stack
  6. Now, remove all the elements of the stack and add them to a new string
  7. You got a reversed string
  8. Add this reversed string to the main string with a white space
  9. 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++){
            StringBuilder sb=new StringBuilder();
            // tracker for adding white spaces after adding each reversed string
                ans.append(" ");

        return ans.toString();

Leave a Reply

Your email address will not be published. Required fields are marked *

WhatsApp Icon Join For Job Alerts