Programming Practice: Reverse a Sentence

Problem: Given a string of words, reverse the string such that the last word becomes the first one. The word itself should not be changed

Examples:

Input: “Hello world”, Output: ” World Hello”
Input: “This blog rocks”, Output: ” rocks blog this”

Algorithm:

1. Initialize two counters, front and back, to the end of the input string
2. While we havent reached the start of the string, move down front we encounter a space. Copy the part of the string from this point until back into the output.
3. Move back down by one character to account for the space. Set front to back, and repeat till front is more than 0.

Java Code:

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s