O(1)空间复杂度、O(n)时间复杂度,要求将一个字符串按单词逆转,比如 This is a sentence,变成sentence a is This
public static void reverse(char[] str, int begin, int end) {
while (begin < end) {
char tmp = str[begin];
str[begin++] = str[end];
str[end--] = tmp;
}
}
public static void reverse(char[] str) {
if (null == str || str.length == 0) {
return;
}
reverse(str, 0, str.length - 1);
int offset = 0;
for (int i = 0; i < str.length; i++) {
if (str[i] == ' ') {
reverse(str, offset, i - 1);
offset = i + 1;
}
}
reverse(str, offset, str.length - 1);
}