Interview Question
1) str = reverse string. ( str can be char array or string buffer) incase of string buffer one can use reverse() function.
2) keep a track of start char index (start) and search for space(end index). If space found reverse the substring from start to end. Continue till the END of the string.
constant space here would be start char index and end character index.
any comments?
Here is working java code based on "reverse string and then reverse each word". It runs in O(1) space and O(n) time complexity.
public static String reverseWords(String str) {
char[] array = str.toCharArray();
reverseChar(array, 0, array.length);
int start = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] == ' ') {
reverseChar(array, start, i);
start = i + 1;
}
}
//Now reverser the final word
reverseChar(array, start, array.length);
return new String(array);
}
private static void reverseChar(char[] array, int startPos, int endPos) {
int size = endPos - startPos;
if (size <= 0) {
throw new IllegalArgumentException("Size can not be " + size);
}
int mid = startPos + (size >> 1);
int lastIndex = endPos - 1;
for (int i = startPos; i < mid; i++) {
char temp = array[i];
array[i] = array[lastIndex];
array[lastIndex--] = temp;
}
}
As we all know Strings is Java are immutable. I would assume the input is in char[] and then use a C-like algorithm to do the reversal in constant space.
- eaparnell December 18, 2009