Reverse A String

!!! UPDATED !!! See below.

Good morning. It is Saturday of Labor Day weekend. The skies in the Twin Cities of Minneapolis and St. Paul are gray and the highs for today are going to be in the mid to upper 60’s. Later today my wife and I will be going to my son’s place to cook paella. My wife and I have been cooking since we were young and we enjoy it. A decade or so ago we purchased a paella pan and have been fixing the dish several times a year. We always make a few changes to the recipe in order to improve on it.

Yesterday my wife and I had dinner at Joan’s in the Park. It is a restaurant in St. Paul. For a fixed price per person each get a four course meal. For each course you get to choose from 5 dishes. The servings are quite small. Our waiter described them as samples for tasting.

The food was good. We paired it with a couple bottles of wine from southern California. We both enjoy the evening and the food. That said; we prefer restaurants that serve average / larger portions. We finished our meal with a milk based pudding. A small drawback on the experience was the lack of espresso coffee. The restaurant is quite small and our waiter told us that they used to have a more capable coffee maker machine, but due to lack of space they switched to a simple drip unit. We recommend the restaurant for the experience more than for the food. By the way you can bring your own wine.

This morning when I woke up I was notified of a Java video about reversing a string using Java. I have not watched the video yet but given that it is about 10 minutes I assume it is going to describe some different approaches. So before I watch the video in steps, I will use the whiteboard and the Eclipse IDE to come with my own code. I can then check how I did as I finish watching the video.

The idea is to convert the string to a character array. We will then reverse the string by copying it in reverse order to a new array. When done will return the string generated by the reverse array of character.

import java.util.Scanner;

public class Solution {
	
	/*
	 * Reverse the specified string.
	 */
	static String reverse(String str) {
				
		// **** no need to reverse ****
		if (str.length() <= 1)
			return str;
		
		// **** array or characters ****
		char[] ar1 = str.toCharArray();
		
		// **** reverse array of characters ****
		char[] ar2 = new char[ar1.length];
		
		// **** reverse the array ****
		for (int i = 0, j = ar2.length - 1; i < ar1.length; i++, j--) ar2[i] = ar1[j]; // **** return the reverse string **** return new String(ar2); } /* * Test scaffolding. */ public static void main(String[] args) { // **** open scaneer **** Scanner sc = new Scanner(System.in); // **** prompt and read string **** System.out.print(">>> str: ");
		String str = sc.nextLine();
		
		// ???? ????
		System.out.println("main <<< str ==>" + str + "<==");
		
		// **** reverse the string ****
		String revStr = reverse(str) ;
		
		// **** ****
		System.out.println("main <<< revStr ==>" + revStr + "<==");
		
		// **** close scanner ****
		sc.close();
	}

}

The main method implements the test scaffolding. We prompt for a string and call the reverse method to reverse it.

The reverse method checks for strings whose length is less than or equal to 1. The reason is that there is nothing to do for such strings.

We put the characters of the string into character array ar1. We create a second array ar2 to place the reversed characters. We then loop through the array reversing the order of the characters. This operation is O(n).

Finally we return a string generated with the character array holding the reversed characters.

>>> str: hello
main <<< str ==>hello<==
main <<< revStr ==>olleh<==

The console capture from the Eclipse IDE shows a run using the same characters we used to develop the code.

Now that we have a solution I will watch the video and will update this post as needed.

UPDATE

It seems like one of the approaches will use StringBuilder. I was going to use StringBuilder in my first approach but after discussing it with my imaginary interviewer we decided to skip it.

	/*
	 * Reverse a string using StringBuilder.
	 */
	static String reverse2(String str) {
		
//		// **** a one liner ****
//		return new StringBuilder(str)
//						.reverse()
//						.toString();
		
		// **** no need to reverse ****
		if (str.length() <= 1)
			return str;

		// **** make a StringBuilder with the specified string ****
		StringBuilder sb = new StringBuilder(str);
				
		// **** reverse the string ****
		sb.reverse();
		
		// **** return the reverse string ****
		return sb.toString();
	}

The code starts the making the same check. I do not know if that is done in the video or not. We then instantiate a StringBuilder using the string passed to the method. We reverse the string and finally we return the string generated from the StringBuilder.

Note that the above code could be implemented in a single line. My preference is to split it for ease of debugging, but it is your choice.

>>> str: hello
>>> str: reverse me
main <<< str ==>reverse me<==
main <<< revStr ==>em esrever<==
main <<< revStr ==>em esrever<==

The output of the Eclipse console now outputs the string we provide and the three reverse approaches we used. The video considers a mixed approach in which you use StringBuilder to build the reverse string one character at a time. This last approach is implemented as reverse3.

	/*
	 * Reverse the stirng using StringBuilder one character at a time.
	 */
	static String reverse3(String str) {
		
		// **** no need to reverse ****
		if (str.length() <= 1) return str; // **** **** StringBuilder sb = new StringBuilder(); // **** **** for (int i = str.length() - 1; i >= 0; i--)
			sb.append(str.charAt(i));
		
		// **** return the reversed string ****
		return sb.toString();
	}

This is the mixed method. We use StringBuilder and we just traverse the original string. Since strings are immutable we do not create multiple strings as reverse the characters in the string.

We create a blank StringBuilder and then traverse the string in reverse order appending the characters to the StringBuilder one character at a time. When done we just return the string associated with the StringBuilder.

>>> str: reverse me
main <<< str ==>reverse me<==
main <<< revStr ==>em esrever<==
main <<< revStr ==>em esrever<==
main <<< revStr ==>em esrever<==

The console now shows the output of the three methods.

The entire code for this project can be found in my GitHub repository.

If you have comments or questions regarding this or any other post in this blog, or if you would like me to help with any phase in the SDLC (Software Development Life Cycle) of a product or service, please do not hesitate and leave me a note below. Requests for help will remain private.

Keep on reading and experimenting. It is the best way to learn and refresh your knowledge!

John

Follow me on Twitter:  @john_canessa

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.