Ben Shi : notes

Reversing a string without temp variables or library functions

So yesterday my friend Jimmy asked me to reverse a string while we were in one of the computers labs at uni. At first I thought “hey, isn’t this like really simple and straightforward, could just use a StringBuffer?”. Then Jimmy said “You can’t use any library functions or temporary variables”. I thought for a second and said “you can do it with arrays” and surely you can definitely do it with arrays as shown by one of our other friend Kevin.

But was that was messy and surely it wasn’t the only solutions. Like many programming problems, this isn’t!

I figured this can be done with a little bit of looping and string manipulation (Note: implementation is in Java). As shown in line 25-27, I looped through the string and reassembled it n times. The reassembling is actually quiet tricky because I reconstructed the original string by cutting and carefully rearranging it every loop. This solution is pretty messy and hard to comprehend without a pen and paper to follow through with it (well at least for me).

It was just past 10 o’clock and I looked at the clock on the top right of my MBP. The time was 10:01 pm, then all of a sudden an idea struck me, I could have just reverse the string using a reverse loop, append it to the original string and cut the palindromic string leaving only the latter half. This solution (line 33-36) was much simpler and easier to remember.

Can’t believe something so simple took me this long to think up. Thank you palindrome!

Leave a Reply