EMChamp Blog

Coding Problem 3 | Reverse String

This problem was originally supposed to be reverse the string in-place. However since I am using Java and Java strings are immutable this was not possible. If you were given a character array instead of a string in java you could reverse that character array in place. The approach I took below was to copy the String into the character array and then reverse it by using the standard reverse string algorithm of swapping array elements 0 and max, 1 and max-1…until floor(max/2). Not a hard problem but a common one asked in many interviews.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

public class ReverseStringCalc {
public String reverseString(String testString) {
char[] s = testString.toCharArray();
for(int i = 0; i < Math.floor(s.length/2);i++) {
if(((s.length-1)-i)==i){
break;
}
char tempChar = s[i];
s[i]=s[(s.length-1)-i];
s[(s.length-1)-i] = tempChar;
}

return new String(s);
}
}