The idea is reverse the string character by character first, then reverse the word character by character. For example, we have string "abc defg hijk". The first step is to reverse the string character by character:
"abc defg hijk" ==> "kjih gfed cba"
Then reverse the word in the output string character by character:
"kjih gfed cba" ==> "hijk defg abc"
The run time is O(n) with constant extra space. Here is the code in java:
public static void resverseString(char[] input) {
reverseString(input, 0, input.length - 1);
int start = 0;
int end = 0;
for (char temp : input) {
if (temp == ' ') {
reverseString(input, start, end - 1);
start = end + 1;
}
end++;
}
reverseString(input, start, end - 1);
}
private static void reverseString(char[] input, int start, int end) {
while (start < end) {
swap(input, start, end);
start++;
end--;
}
}
private static void swap (char[] input, int i, int j) {
char temp = input[i];
input[i] = input[j];
input[j] = temp;
}
No comments:
Post a Comment