Reverse Words in a String Algorithm

Today we will try to solve “Reverse Words in a String” task for leetcode.

Task description:

Given an input string, reverse the string word by word.

For example,
Given s = “the sky is blue“,
return “blue is sky the“.

Clarification:

  • What constitutes a word?
    A sequence of non-space characters constitutes a word.
  • Could the input string contain leading or trailing spaces?
    Yes. However, your reversed string should not contain leading or trailing spaces.
  • How about multiple spaces between two words?
    Reduce them to a single space in the reversed string.

Stop and think…

You can see that is easy task. I think there are a lot ways to solve this task I will provide just a one. So, what is the solution can be ?

For example:

–  we can create new one string and goes through input string from end to start  and copy all elements from input to created string, can work ? Why not …

– we can create four indexes like next

        int firstWordStart = 0;
        int firstWordEnd = 0;
        int lastWordStart = s.length()-1;
        int lastWordEnd = s.length()-1;

and work with these indexes, till

firstWordEnd < lastWordStart

but we should manage string with shifting all words because length of first and last words can be diff, So, That is hard but can be solution with swap in place.

– we can use recursion and if we found whitespace start next recursion cycle with string without first word and after recursion add first word to the end (it’s like Reverse LinkedList {Recursion implementation} ), that is good solution, but can be problem with stack memory.

– we can split words by whitespace char ” ” and reverse all words in splitted array after that create result string from array, that solution like first but more elegant for my point of view, so, I am going to implement the solution (leetcode accepted it, so, it’s right 🙂 )

public String reverseWords(String s) {
       s = s.trim();
       String [] data = s.split(" ");
       int lastIndex = data.length-1;
       for(int i = 0; i < data.length/2; i++){
        swap(data, i, lastIndex);
        lastIndex--;
       }
       return returnString(data);
    }
 
    void swap(String[] data, int startIndex, int endIndex){
        String temp;
        temp = data[endIndex];
        data[endIndex] = data[startIndex];
        data[startIndex] = temp;
    }
 
    String returnString(String [] data){
        StringBuilder result = new StringBuilder();
        for(String datum:data){
            if(datum!=null && datum.trim().length()!=0)
                result.append(datum).append(" ");
        }
        return result.toString().trim();
    }

So, we have 3 methods, first is main and executing main logic.

Next one swap, swap is very easy, just swapping elements in array.

Last one is reversed string creator.

So, that is all…

Cheers !

Read More Post

STAY CONNECTED

Most Popular

Why Serviced Apartments Are the Perfect Choice for Long-Term Stays in Singapore – Everything You Need to Know
17 Dec

Why Serviced Apartments Are the Perfect Choice for Long-Term Stays in Singapore – Everything You Need to Know

If you’re heading to Singapore for a few weeks or many months, maybe for work or study or just to

Manifesting Your Dream Career: Finding Your Passion And Purpose
01 Aug

Manifesting Your Dream Career: Finding Your Passion And Purpose

Are you passionate about finding your dream career? Manifesting can help you align your career with your passions and purpose.

Revolutionizing Your Ride: Expert Auto Service At Carolina Auto Service
27 Feb

Revolutionizing Your Ride: Expert Auto Service At Carolina Auto Service

Finding a reliable auto service provider is paramount in the bustling world of vehicle maintenance and repair. That's where Carolina

Floratam: The Robust Grass Solution From Council Growers SOD
25 Jan

Floratam: The Robust Grass Solution From Council Growers SOD

Floratam grass, a popular St. Augustine variety, has become a go-to choice for homeowners and landscapers seeking a lush, durable

Carolina Mobile Autoservice: Your Go-To For Expert Brake Service Repair
25 Jan

Carolina Mobile Autoservice: Your Go-To For Expert Brake Service Repair

For vehicle owners, the braking system is among the most critical components for safety and performance. Carolina Mobile Autoservice, a

Safeguarding Your Property: Expert Water Damage Services By MBC Capital
24 Jan

Safeguarding Your Property: Expert Water Damage Services By MBC Capital

Water damage can significantly impact homes and businesses, often leaving a trail of destruction and disruption in its wake. Understanding